0

我试图找出两个日期之间的差异,它应该以天为单位显示。

NSLog(@"%@", [NSDate date]);

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd/mm/yyyy"];

NSDate *formattedDate = [formatter dateFromString: [NSString stringWithFormat:@"31/05/2013"]];


NSDate *startDateForDays = [NSDate date];
NSDate *endDateForDays = formattedDate;

NSCalendar *gregorian = [[NSCalendar alloc]
                         initWithCalendarIdentifier:NSGregorianCalendar];

NSUInteger unitFlagsForDays = NSDayCalendarUnit;

NSDateComponents *componentsForDays = [gregorian components:unitFlagsForDays
                                                   fromDate:startDateForDays
                                                     toDate:endDateForDays options:0];

NSLog(@"%@", [NSString stringWithFormat:@"%i days until %@", [componentsForDays day], formattedDate]);

输出如下所示:

2013-05-29 20:21:51 +0000
118 days until 2013-01-30 23:05:00 +0000

我不知道我的代码有什么问题,希望你能帮助我。

4

2 回答 2

1

试试这个------------>

NSTimeInterval diff = [secondDate timeIntervalSinceDate:startDate];

于 2013-05-29T20:36:59.013 回答
1

我意识到你已经解决了你的问题,只是指出你可以通过省略无符号整数位来简化一点。

NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit
                                                fromDate:startDate
                                                  toDate:endDate
                                                 options:0];

这应该是评论而不是答案,但即使我应该能够发表评论,我也无法发表评论。

于 2013-05-29T20:50:35.767 回答