【发布时间】:2017-02-11 13:48:01
【问题描述】:
我有两个从 UTC 日期开始的 NSDate。 让我们称他们为(A 和 B)
我知道 A 代表中国的一天,B 代表美国的一天。 (我知道时区。)如何计算两者之间的天数差异...?
我一直在使用下面的方法,显然是不正确的。
class func daysDifferenceIn(firstDate: NSDate, firstTimeZone: String, secondDate: NSDate, secondTimeZone: String) -> Int {
objc_sync_enter(self)
let firstDateComponents = NSCalendar.CommonCalendar.componentsInTimeZone(NSTimeZone(name: firstTimeZone)!, fromDate: firstDate)
let secondDateComponents = NSCalendar.CommonCalendar.componentsInTimeZone(NSTimeZone(name: secondTimeZone)!, fromDate: secondDate)
NSCalendar.CommonCalendar.timeZone = NSTimeZone(name: firstTimeZone)!
let firstCalDate = NSCalendar.CommonCalendar.dateFromComponents(firstDateComponents)
NSCalendar.CommonCalendar.timeZone = NSTimeZone(name: secondTimeZone)!
let secondCalDate = NSCalendar.CommonCalendar.dateFromComponents(secondDateComponents)
objc_sync_exit(self)
return firstCalDate!.numberOfDaysUntilDateTime(secondCalDate!)
}
func numberOfDaysUntilDateTime(toDateTime: NSDate, inTimeZone timeZone: NSTimeZone? = nil) -> Int {
let calendar = NSCalendar.CommonCalendar
if let timeZone = timeZone {
calendar.timeZone = timeZone
}
var fromDate: NSDate?, toDate: NSDate?
calendar.rangeOfUnit(.Day, startDate: &fromDate, interval: nil, forDate: self)
calendar.rangeOfUnit(.Day, startDate: &toDate, interval: nil, forDate: toDateTime)
let difference = calendar.components(.Day, fromDate: fromDate!, toDate: toDate!, options: [])
return difference.day
}
我可以手动从 firstDateComponents 和 secondDateComponents 中减去日分量,这是我不想做的,因为我必须寻找 31 和 28 等边缘情况。
任何帮助表示赞赏。谢谢。
更新
第一个日期是 2017-02-10 16:15:00 +0000 第二个日期是 2017-02-11 03:20:00 +0000 两者都是 UTC。
firstTimeZone 字符串“亚洲/上海” secondTimeZone 字符串 "America/Los_Angeles"
所以天差是-1天。基本上我正在实施航班状态,当航班在起飞前 1 天降落时,您可以看到以下链接。因为它从西飞到东。
https://www.google.co.in/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=ua+890
也是对日期组件的描述。
Printing description of firstDateComponents:
<NSDateComponents: 0x600000142310>
Calendar: <CFCalendar 0x60000088b6d0 [0x10c5d3df0]>{identifier = 'gregorian'}
TimeZone: Asia/Shanghai (GMT+8) offset 28800
Era: 1
Calendar Year: 2017
Month: 2
Leap month: no
Day: 11
Hour: 0
Minute: 15
Second: 0
Nanosecond: 0
Quarter: 0
Year for Week of Year: 2017
Week of Year: 6
Week of Month: 2
Weekday: 7
Weekday Ordinal: 2
Printing description of secondDateComponents:
<NSDateComponents: 0x60000014b8f0>
Calendar: <CFCalendar 0x60000049b620 [0x10c5d3df0]>{identifier = 'gregorian'}
TimeZone: America/Los_Angeles (PST) offset -28800
Era: 1
Calendar Year: 2017
Month: 2
Leap month: no
Day: 10
Hour: 19
Minute: 20
Second: 0
Nanosecond: 0
Quarter: 0
Year for Week of Year: 2017
Week of Year: 6
Week of Month: 2
Weekday: 6
Weekday Ordinal: 2
【问题讨论】:
-
如果这两个日期在中国是同一天,而在美国是不同的日子,你会期待什么结果?
-
@MartinR 你可以看到我对这个问题的更新。
-
@JoshCaswell:确实。现在多次阅读了这个问题,这似乎是这里真正想要的。
标签: ios swift nsdate nsdatecomponents