Oleg
Oleg

Reputation: 3014

iOS - Create NSDate without hours/minutes and ignoring daylight saving shifts

I'm trying to remove hours and minutes from my NSDate object

keyDate = [[array objectAtIndex:i] date];
unsigned int flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSCalendar* calendar = [NSCalendar currentCalendar];

NSDateComponents* components = [calendar components:flags fromDate:keyDate];
keyDate = [[calendar dateFromComponents:components] dateByAddingTimeInterval:[[NSTimeZone localTimeZone]secondsFromGMT]];

and it works fine until April 2013, after that my NSDate objects are created with -1 hour shift. I'm pretty sure it is because daylight saving time.

How can I make my NSDate objects be 00:00:00 +0000 during all year ?

Upvotes: 4

Views: 1470

Answers (1)

gaige
gaige

Reputation: 17471

NSDate objects are inherently stored as GMT values. The problem you're running into here is that you're doing calculations using the currentCalendar (which might be in DST at the moment) and the localTimeZone secondsFromGMT, which switches depending on the time of year.

The best solution here is to use an NSCalendar that is GMT instead of based on a timezone that shifts, if (as you indicate) you want them to be +0000 at all times.

Alternatively, you can change to use NSTimeZone's secondsFromGMTForDate: which takes into account DST at the date/time in question.

Upvotes: 6

Related Questions