两个 NSDate 之间的天数

本教程将介绍两个 NSDate 之间的天数的处理方法,这篇教程是从别的地方看到的,然后加了一些国外程序员的疑问与解答,希望能对你有所帮助,好了,下面开始学习吧。

两个 NSDate 之间的天数 教程 第1张

问题描述

How could I determine the number of days between two NSDate values (taking into consideration time as well)?

The NSDate values are in whatever form [NSDate date] takes.

Specifically, when a user enters the inactive state in my iPhone app, I store the following value:

exitDate = [NSDate date];

And when they open the app back up, I get the current time:

NSDate *now = [NSDate date];

Now I'd like to implement the following:

-(int)numberOfDaysBetweenStartDate:exitDate andEndDate:now

解决方案

Here's an implementation I used to determine the number of calendar days between two dates:

+ (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];
}

EDIT:

Fantastic solution above, here's Swift version below as an extension on 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
  }
}

A bit of force unwrapping going on which you may want to remove depending on your use case.

The above solution also works for time zones other than the current time zone, perfect for an app that shows information about places all around the world.

好了关于两个 NSDate 之间的天数的教程就到这里就结束了,希望趣模板源码网找到的这篇技术文章能帮助到大家,更多技术教程可以在站内搜索。