IOS - creating NSDate without hours / minutes and ignoring daylight saving time shifts

I am 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 works fine until April 2013, after which my NSDate objects are created with a -1-hour shift. I am sure it is because of summer time.

How can I make NSDate objects 00:00:00 +0000 all year long?

+4
source share
1 answer

NSDate objects are essentially stored as GMT values. The problem you are facing is that you are doing calculations using currentCalendar (which may be in DST at the moment) and localTimeZone secondsFromGMT, which switches depending on the time of year.

The best solution here is to use NSCalendar, which is GMT instead of being based on a time zone that moves if (as you specify) you want them to always be +0000.

Alternatively, you can change the use of NSTimeZone secondsFromGMTForDate: which takes into account the DST for the date / time in question.

+6
source

Source: https://habr.com/ru/post/1443203/


All Articles