NSDateComponents Question - Wrong Day

I have an NSDateComponents problem. I have two NSDates that I am trying to compare by checking if their year, month and day match. I do this by converting 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]); } 

My result does not match, day: 3 against 4. Why should it be?

I read with great interest the following questions: NSDateComponents - the method of the day that returns the wrong day and https://stackoverflow.com/questions/3920445/nsdatecomponents-incorrectly-reporting-day however do not answer my question why this does not work.

Any tips?

+4
source share
3 answers

I think the problem is the following: Your dates are set in the GMT time zone (+0000) If you are in the USA, for example, on GTM-6, then using -currentCalendar first date will be 6:00 on August 3, and the second date it will be 8:49 a.m. on August 4.

You must force your calendar to have a UTC time zone (GMT) or put dates in your time zone, depending on what is appropriate for your application.

+6
source

It looks like you have a time zone problem. Although your dates are set in time zone +0000, your call to [NSCalendar calendar] will most likely return a calendar for your local time zone. Given the local time adjustment, orderDate is likely the next day. Manually set the calendars in the time zone +0000.

+2
source

NSDate has the function isEqualToDate :. therefore, what you are trying to do can be done:

 [datea isEqualToDate:dateb]; 

there is also a Compare: function that returns the order of dates.

edit: Now I know that this does not answer your question about why days return different values ​​when they are set the same way. Sorry it can still help make your code a little cleaner.

+1
source

All Articles