我正在尝试制作一个标签,说明事件发生了多少天。我想计算今天的日期和事件日期之间的差异。我正在使用此代码,它给我-4600。它工作正常,直到我使用今天的日期。
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:@"yyyy-MM-dd"];
NSDate *startDate = [NSDate date];
NSDate *endDate = [f dateFromString:end];
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit
fromDate:startDate
toDate:endDate
options:0];
return components.day;
return components.day;
答案 0 :(得分:15)
默认情况下[NSDate date]
返回日期,如2013-08-06 08:50:25 +0000
并且您已将格式化程序设置为yyyy-MM-dd
,因此您必须将startDate转换为yyyy-MM-dd
此格式..
试试这个
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:@"yyyy-MM-ddHH:mm:ss ZZZ"];
NSDate *startDate = [NSDate date];
NSLog(@"%@",startDate);
NSDate *endDate = [f dateFromString:end];
NSLog(@"%@",endDate);
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit
fromDate:startDate
toDate:endDate
options:0];
return components.day;