lundi 2 février 2015

NSDate loses and hour when adding a month during DST change?

When trying to add a month using the suggested 'correct' method on all the stackoverflow questions I can find, the date I get back always loses an hour due to DST.



NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

NSDateComponents *component = [[NSDateComponents alloc] init];
[component setDay:29];
[component setMonth:3];
[component setYear:2015];
NSDate *date = [gregorian dateFromComponents:component];
NSLog(@"Date: %@", date);

NSDateComponents *monthComponent = [[NSDateComponents alloc] init];
monthComponent.month = 1;

NSDate *newDate = [gregorian dateByAddingComponents:monthComponent toDate:date options:0];

NSLog(@"newDate: %@", newDate);


The output of this code is:


Date: 2015-03-29 00:00:00 +0000


newDate: 2015-04-28 23:00:00 +0000


How can I add a month across a DST change and keep the time at midnight?


Thanks for any help.




Aucun commentaire:

Enregistrer un commentaire