如何确定两个 NSDate
值之间的天数(同时考虑时间)?
NSDate
值是 [NSDate date]
采用的任何形式。
具体来说,当用户在我的 iPhone 应用程序中进入非事件状态时,我会存储以下值:
exitDate = [NSDate date];
当他们打开应用程序备份时,我会得到当前时间:
NSDate *now = [NSDate date];
现在我想实现以下内容:
-(int)numberOfDaysBetweenStartDate:exitDate andEndDate:now
最佳答案
这是我用来确定两个日期之间的日历天数的实现:
+ (NSInteger)daysBetweenDate:(NSDate*)fromDateTime andDate:(NSDate*)toDateTime
{
NSDate *fromDate;
NSDate *toDate;
NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar rangeOfUnit:NSCalendarUnitDay startDate:&fromDate
interval:NULL forDate:fromDateTime];
[calendar rangeOfUnit:NSCalendarUnitDay startDate:&toDate
interval:NULL forDate:toDateTime];
NSDateComponents *difference = [calendar components:NSCalendarUnitDay
fromDate:fromDate toDate:toDate options:0];
return [difference day];
}
编辑:
上面的解决方案很棒,下面是 Swift 版本作为 NSDate
的扩展:
extension NSDate {
func numberOfDaysUntilDateTime(toDateTime: NSDate, inTimeZone timeZone: NSTimeZone? = nil) -> Int {
let calendar = NSCalendar.currentCalendar()
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
}
}
根据您的用例,您可能希望移除一些强制展开。
上述解决方案也适用于当前时区以外的时区,非常适合显示世界各地信息的应用。
关于ios - 两个 NSDate 之间的天数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4739483/