I am geting some weird result from NSDateComponents and NSDateFormatter.
I have the following method to set the hour to 10am for the given date
+ (NSDate *)getTenOClockOnDate:(NSDate*)inputDate { NSCalendar *cal = [NSCalendar autoupdatingCurrentCalendar]; NSDateComponents *components = [cal components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSWeekCalendarUnit | NSWeekdayCalendarUnit ) fromDate:inputDate]; [components setHour:10]; [components setMinute:0]; [components setSecond:0]; // construct new date and return NSDate *newDate = [cal dateFromComponents:components]; NSLog(@"input date: %@ -- new date: %@", inputDate, newDate); return newDate; } While I make the following call:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"yyyy-MM-dd"]; [MyUtils getTenOClockOnDate:[dateFormatter dateFromString:@"2010-12-31"]]; [MyUtils getTenOClockOnDate:[dateFormatter dateFromString:@"2011-01-01"]]; [MyUtils getTenOClockOnDate:[dateFormatter dateFromString:@"2011-01-02"]]; only the the second line, I get the unexpected result:
input date: 2010-12-31 05:00:00 GMT -- new date: 2010-12-31 15:00:00 GMT input date: 2011-01-01 05:00:00 GMT -- new date: 2011-12-31 15:00:00 GMT input date: 2011-01-02 05:00:00 GMT -- new date: 2011-01-02 15:00:00 GMT The problem is on the second record, 2011-01-01, it turns into 2011-12-31 just by setting the hour to 10.