ios - 比较 2 个日期让我在 IOS 中少了 1 天

标签 ios iphone objective-c nsdate nsdatecomponents

我正在尝试比较 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的建议,您还可以设置NSCalendartimezone,例如,

[calendar setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];

要将 otherDaytodaydate 进行精确比较,请参阅 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/

相关文章:

iphone - 如何在不更改 iPhone 应用程序中的设备方向的情况下更改应用程序的方向

python - Objective-C 中是否存在类似 Python 生成器的东西?

ios - 如何知道哪个单元格打开了 UiTableViewController?

ios - 在常量初始化中使用 IBoutlet

ios - 在 iPhone 上播放声音样本

iphone - 后台本地通知

php - 带有企业应用程序的 Apple 推送通知

ios - 添加约束后文本不会显示

ios - 将 NSString 转换为其他 NSString

ios - #define 的问题 - "="标记之前的预期表达式