如何在Swift中正确计算日期时间差 [英] How to calculate date time difference properly in Swift
问题描述
我想计算两个日期之间的时差,并且时差结果必须类似
I want to calculate time difference between 2 dates, and the time difference result must be something like
7h 12m OR 4 d 5h 27m OR 1M 5d 3h 21m
7h 12m OR 4 d 5h 27m OR 1M 5d 3h 21m
我试图编写这样的函数:
I have tried to write a function like this:
import UIKit
func calculateTimeDifference(from dateTime1: String, to dateTime2: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateAsString = dateTime1
let date1 = dateFormatter.date(from: dateAsString)!
let dateAsString2 = dateTime2
let date2 = dateFormatter.date(from: dateAsString2)!
let components : NSCalendar.Unit = [.second, .minute, .hour, .day, .weekOfMonth, .month, .year]
let difference = (Calendar.current as NSCalendar).components(components, from: date1, to: date2, options: [])
var dateTimeDifferenceString = ""
if difference.day != 0 {
dateTimeDifferenceString = "\(difference.day!)d \(difference.hour!)h \(difference.minute!)m"
} else if difference.day == 0 {
dateTimeDifferenceString = "\(difference.hour!)h \(difference.minute!)m"
}
return dateTimeDifferenceString
}
但是当我实现这段代码时
but when I implement this code
let checkinTime = "2018-02-09 07:51:01"
let now = "2018-02-20 14:56:18"
calculateTimeDifference(from: checkinTime, to: now)
// Result: "4d 7h 5m"
我不知道为什么是4天而不是11天
I don't know why it just 4 days instead of 11 days
但是如果我在同一天实施它,它将给出正确的结果
but if I implement it in the same day, it gives correct result
let checkinTime = "2018-02-09 07:51:01"
let now = "2018-02-09 14:56:18"
calculateTimeDifference(from: checkinTime, to: now)
// "7h 5m"
这里出了什么问题?
推荐答案
在您的第一种情况下,日期之间的差是一个星期,四天后,您会看到,如果您打印计算出的日期部分.
In your first case, the difference between the dates is one week and four days, you'll see that if you print the computed date components.
print(difference)
// year: 0 month: 0 day: 4 hour: 7 minute: 5 second: 17 weekOfMonth: 1 isLeapMonth: false
// ^^^^^^ ^^^^^^^^^^^^^^
所以这就是为什么您得到输出"4d 7h 5m"而不是预期为"11d 7h 5m".要解决此问题,只需删除 .weekOfMonth
从日历单位开始:
So that's why you get the output "4d 7h 5m" instead of the
expected "11d 7h 5m". To solve the problem, just remove .weekOfMonth
from the calendar units:
let components : NSCalendar.Unit = [.second, .minute, .hour, .day, .month, .year]
此外,您可以直接与 Calendar
一起使用,而无需桥接到 NSCalendar
:
In addition, you can work with Calendar
directly, without
bridging to NSCalendar
:
let components: Set<Calendar.Component> = [.second, .minute, .hour, .day, .month, .year]
let difference = Calendar.current.dateComponents(components, from: date1, to: date2)
这篇关于如何在Swift中正确计算日期时间差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!