【发布时间】:2016-10-29 16:18:57
【问题描述】:
我正在计算两个日期之间的时间差。我有一段代码:
func timeAgoSinceDate(_ date:Date, numericDates:Bool) -> String {
let calendar = Calendar.current
let now = Date()
let components:DateComponents = (calendar as NSCalendar).components([NSCalendar.Unit.minute , NSCalendar.Unit.hour , NSCalendar.Unit.day , NSCalendar.Unit.weekOfYear , NSCalendar.Unit.month , NSCalendar.Unit.year , NSCalendar.Unit.second], from: now, to: date, options: NSCalendar.Options())
print(now)
print(date)
print(components.month)
这些是我在控制台中看到的一些示例:
2016-10-29 16:12:34 +0000
2017-03-29 16:03:13 +0000
Optional(4) //I think it should return 5?
2016-10-29 16:12:34 +0000
2017-01-29 17:03:13 +0000
Optional(2) //again, why 2 instead of 3?
2016-10-29 16:12:34 +0000
2015-09-30 15:54:20 +0000
Optional(0) //why 0 since it's almost whole year?
2016-10-29 16:12:34 +0000
2016-05-29 14:09:31 +0000
Optional(-5) //this seems to be fine
等等...这里有什么问题?
我遇到的问题是日期计算。在我正在做的代码中:
if (components.month! >= 2) {
return "in \(components.month!) months"
} else if (components.month! >= 1){
if (numericDates){
return "in 1 month"
} else {
return "in one month"
}
}
else if (components.month! <= -2) {
return "\(components.month!) months ago"
} else if (components.month! <= -1){
if (numericDates){
return "1 month ago"
} else {
return "one month ago"
}
}
然后,由于我的计算,当前当一个日期是2016-10-29 16:32:54 +0000,另一个是2017-01-29 17:03:13 +0000,用户看到in 2 months。那是因为整个print(components) 返回:
year: 0 month: 2 day: 2 hour: 23 minute: 30 second: 18 weekOfYear: 4 isLeapMonth: false
但在现实生活中它应该返回 3,因为它是 10 月和 1 月之间的差异。有没有比一堆if 将所有内容四舍五入的语句更好的方法来计算这种差异?
【问题讨论】:
-
你在哪个时区?日期以 UTC/GMT 打印,但日历计算在您的本地日历/时区完成。
-
在您的第一个示例中,给定日期之间 小于 5 个月,因此结果 4 是正确的。
-
hm 但我认为在
months的情况下时区不应该影响计算...无论如何,我在GMT +1,有什么方法可以独立于时区进行计算? -
您可以将日历时区设置为 GMT,但即便如此,在第一个示例中您会得到 4 而不是 5,在第三个示例中会得到 0,因为差异是 less 一年多。试试
print(components)看看实际的区别。 -
几乎在编程方面是不是;-)
标签: ios swift nsdate nsdatecomponents