我正在尝试比较 2 个日期,但我少了 1 天
这是一个片段:
NSDateComponents* dateComponents = [[NSDateComponents alloc] init];
[dateComponents setYear: 2014];
[dateComponents setMonth: 1];
[dateComponents setDay: 31];
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDate* otherDay = [calendar dateFromComponents: dateComponents];
NSDate * todaydate= [NSDate date];
if ([otherDay compare:todaydate]>= NSOrderedDescending)
{
NSLog(@"In If other Date= %@ & Today = %@ ", otherDay,todaydate);
}else
{
NSLog(@"I am in else other date= %@ and today = %@ ",otherDay, todaydate);
}
我得到的日志是:
I am in else other date= 2014-01-30 18:30:00 +0000 and today = 2014-01-31 08:34:21 +0000
为什么显示其他 date = 2014 年 1 月 30 日?
最佳答案
您需要设置NSDateComponents
的时区,例如,
[dateComponents setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
或者根据trojanfoe的建议,您还可以设置NSCalendar
的timezone,例如,
[calendar setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
要将 otherDay 与 todaydate 进行精确比较,请参阅 Martin R 的答案,您需要设置
NSDate * todaydate;
[calendar rangeOfUnit:NSDayCalendarUnit startDate:&todaydate interval:NULL forDate:[NSDate date]];
Martin R 的 回答非常有用。
关于ios - 比较 2 个日期让我在 IOS 中少了 1 天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21475156/