如何查找天数

时间:2012-12-16 14:25:32

标签: iphone objective-c ios ipad nsdate

  

可能重复:
  iPhone - get number of days between two dates

我正在尝试比较两个日期,并找出它们之间的天数。

如下所示:

now = [NSDate date];

// This is i am saving in NSUSerdefault on some condition,like 

if (a == 1) {

    dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd HH:MM:SS";
    [dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
    NSLog(@"The Current Time is %@",[dateFormatter stringFromDate:now]);
    datesaved = [NSString stringWithFormat:@"%@",[dateFormatter stringFromDate:now]];
    NSLog(@"old date saved : %@",datesaved);

    [dateFormatter release];
}

和 找到当前日期。

现在我想将当前日期与NSUserDefaults中保存的日期进行比较,以查找它们之间的天数。

前:

  

当前时间是2012-12-16 19:12:74   旧日期已保存:2012-12-12   19:12:74

天数:4

由于

2 个答案:

答案 0 :(得分:1)

NSDate *date1 = [NSDate dateWithString:@"2010-01-01 00:00:00 +0000"];
NSDate *date2 = [NSDate dateWithString:@"2010-02-03 00:00:00 +0000"];

NSTimeInterval secondsBetween = [date2 timeIntervalSinceDate:date1];

int numberOfDays = secondsBetween / 86400;

NSLog(@"There are %d days in between the two dates.", numberOfDays);

答案 1 :(得分:1)

您可以通过这种方式获取日期的日期组件:

NSDate* now = [NSDate date]; // Or date from format
NSCalendar* cal = [NSCalendar currentCalendar];
NSDateComponents* components = [cal components: NSDayCalendarUnit fromDate: now];
NSInteger day = [components day];

对另一个日期做同样的事情并进行比较。