NSDateComponents问题 - 错误的一天 [英] NSDateComponents issue - incorrect day

查看:257
本文介绍了NSDateComponents问题 - 错误的一天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个NSDateComponents问题。我有两个NSDates,我试图通过检查他们的年,月和日匹配来比较。我这样做是通过将NSDate值转换为这些整数组件,如下所示:

I have a NSDateComponents problem. I have two NSDates that I am trying to compare by checking if their year, month and day match. This I am doing by converting the NSDate values to these integer components as follows:

//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 vs. 4.为什么会这样是吗?

My result is Not Matched, Day: 3 vs. 4. Why would this be?

我非常感兴趣地阅读了以下问题:
NSDateComponents - 返回错误日期的日方法
https://stackoverflow.com/questions/3920445/nsdatecomponents-incorrectly-reporting-day 但是我们都没有回答为什么这不起作用的问题。

I have read with great interest the following questions: NSDateComponents - day method returning wrong day and https://stackoverflow.com/questions/3920445/nsdatecomponents-incorrectly-reporting-day however neither answer my question of why this is not working.

任何建议?

推荐答案

我认为问题如下:
您的日期是按照格林威治标准时间的zone(+0000)
如果您在美国,例如GTM-6,那么通过 -currentCalendar ,第一个日期将是8月3日下午6点而第二个日期将是8月4日上午8:49。

I think the issue is the following: Your dates are set in GMT time zone (+0000) If you are in the US, for example at GTM-6, then by the -currentCalendar the first date will be 6pm on Aug 3rd while second date will be 8:49am on Aug 4th.

你应该强制你的日历有U TC(GMT)时区,或将日期放在您的时区,具体取决于您的申请。

You should force your calendar to have the UTC (GMT) timezone, or put the dates in your time zone, depending what is correct for your application.

这篇关于NSDateComponents问题 - 错误的一天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆