0

可能重复:
iPhone - 获取两个日期之间的天数

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

如下所示:

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

谢谢

4

2 回答 2

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);
于 2012-12-16T14:40:54.913 回答
1

您可以通过这种方式获取日期的日期部分:

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

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

于 2012-12-16T14:57:16.383 回答