Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDateComponents issue - incorrect day

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]);
 }

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

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.

Any advice?

like image 240
hocker Avatar asked Jan 19 '23 01:01

hocker


1 Answers

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.

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.

like image 70
Jacob Gorban Avatar answered Jan 31 '23 06:01

Jacob Gorban