我有一个 NSDateComponents 问题。我有两个 NSDate,我试图通过检查它们的年、月和日是否匹配来进行比较。我通过将 NSDate 值转换为这些整数分量来完成此操作,如下所示:
//NSDate *cgiDate is previously set to 2011-08-04 00:00:00 +0000
//NSDate *orderDate is previously set to 2011-08-04 14:49:02 +0000
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *cgiDateComponents = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit ) fromDate:cgiDate];
NSCalendar *orderCalendar = [NSCalendar currentCalendar];
NSDateComponents *orderDateComponents = [orderCalendar components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit ) fromDate:orderDate];
if (([cgiDateComponents day] == [orderDateComponents day]) &&
([cgiDateComponents month] == [orderDateComponents month]) &&
([cgiDateComponents year] == [orderDateComponents year])) {
GHTestLog(@"MATCHED");
} else {
GHTestLog(@"Not matched");
GHTestLog(@"Day: %d vs. %d", [cgiDateComponents day], [orderDateComponents day]);
}
我的结果是不匹配,第 3 天与第 4 天。为什么会这样?
我饶有兴趣地阅读了以下问题:NSDateComponents - 返回错误日期的日期方法 and
https://stackoverflow.com/questions/3920445/nsdatecomponents-in Correctly-reporting-day然而,两者都没有回答我为什么这不起作用的问题。
有什么建议吗?
我认为问题如下:
您的日期设置为 GMT 时区 (+0000)
如果您在美国,例如在 GTM-6,则通过-currentCalendar
第一次约会将于 8 月 3 日下午 6 点进行,第二次约会将于 8 月 4 日上午 8:49 进行。
您应该强制日历使用 UTC (GMT) 时区,或者将日期放入您的时区,具体取决于您的应用程序的正确情况。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)