ios - 两个 NSDate 之间的天数

如何确定两个 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
  }
}

根据您的用例,您可能希望移除一些强制展开。

上述解决方案也适用于当前时区以外的时区,非常适合显示世界各地信息的应用。

https://stackoverflow.com/questions/4739483/

相关文章:

ios - 如何确定 NSDate 是否是今天?

ios - 如何手动弃用成员

objective-c - NSAttributedString 的 boundingRectWit

objective-c - 为什么要使用 ivar?

ios - 如何在 iPhone 上创建圆角 UILabel?

ios - 如何查看 NSString 是否以某个其他字符串开头?

iphone - 静态库中的 Objective-C 类别

objective-c - 在objective-c中YES/NO,TRUE/FALSE和true/

iphone - 以编程方式切换到 TabBar 选项卡 View ?

objective-c - xcode中Base SDK、iOS部署目标、Target、Projec