【问题标题】:Comparing 2 dates gives me 1 day less in comparison in IOS比较 2 个日期让我在 IOS 中减少了 1 天
【发布时间】:2014-02-23 20:35:03
【问题描述】:

我正在尝试比较 2 个日期,但我少了 1 天

这是一个sn-p:

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 = 30th jan 2014

【问题讨论】:

  • 读起来像一个off-by-1错误,但不熟悉iOS框架的那个方面,我只能暗示解决方案。尝试使用 earlyDate:、isEqual: 和 laterDate: 而不是 compare: 看看问题是否仍然存在
  • 我想问题是 GMT 偏移量

标签: ios iphone objective-c nsdate nsdatecomponents


【解决方案1】:

你需要设置NSDateComponents时区,比如,

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

或者根据trojanfoe的建议你也可以设置NSCalendartimezone之类的,

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

要准确比较 otherDaytodaydate,请查看您需要设置的 Martin R 的回答

NSDate * 今天日期;
[calendar rangeOfUnit:NSDayCalendarUnit startDate:&todaydate interval:NULL forDate:[NSDate date]];

来自 Martin R 的 的回答非常有用。

【讨论】:

  • 您也应该在dateComponents 中设置该日历。但是,由于我住的地方,我无法重现 OP 的问题。
  • 不,我的意思是[dateComponents setCalendar:calendar];(更改代码顺序,先获取日历)。
  • 抱歉,我认为这不是正确的解决方案。通过将时区设置为 GMT,您将 otherDay 计算为“2014-01-31 00:00 +0000”,即印度时区的“2014-01-31 05:30”。如果您想检查今天在印度是否为 2014-01-31,这是不正确的。 - 所以它“修复”了“显示问题”(这不是真正的问题),但不是与“今天”的错误比较。
  • @MartinR - 是的,你是对的,感谢您提高我的知识 :)
【解决方案2】:

您的问题有两个不同的方面。首先,

NSDateComponents* dateComponents = [[NSDateComponents alloc] init];
[dateComponents setYear: 2014];
[dateComponents setMonth: 1];
[dateComponents setDay: 31];
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDate* otherDay = [calendar dateFromComponents: dateComponents];

otherDay 计算为“2014-01-31 00:00”(在您的时区),并且

NSDate *todaydate = [NSDate date];

todaydate 计算为当前时间点,其中包括小时、分钟 和秒,例如“2014-01-31 13:00:00”(在您的时区)。因此

[otherDay compare:todaydate]

返回NSOrderedAscendingotherDaytodaydate

您可能想要将todaydate 计算为当天的开始 (今天 00:00)。这可以这样做

NSDate * todaydate;
[calendar rangeOfUnit:NSDayCalendarUnit startDate:&todaydate interval:NULL forDate:[NSDate date]];

现在[otherDay compare:todaydate] 返回NSOrderedSame,正如您所料。


另一方面是NSLog 输出。用NSLog() 打印NSDate 根据 GMT 打印日期,您所在时区的“2014-01-31 00:00”是 与格林威治标准时间“2014-01-30 18:30:00 +0000”完全相同

输出是正确的,它只是使用 GMT 而不是你当地的时区来显示。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-08
    • 1970-01-01
    • 2012-11-27
    • 1970-01-01
    • 1970-01-01
    • 2011-09-01
    • 2015-08-22
    相关资源
    最近更新 更多