So I use this method to convert a string to NSDate. Hours before, it works correctly, but suddenly the NSDateComponents
returns a wrong date. I have no clue why.
- (NSDate *)NSDateFromDate: (NSString *) str
{
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:@"yyyy-MM-dd"];
NSDate *date = [formatter dateFromString:str];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
// extracting components from date
unsigned units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit;
NSDateComponents *components = [calendar components:units fromDate:date];
int dayIndex = [components weekday]; // sunday = 1
int dayDate = [components day];
NSLog(@"%@ => %@ (date = %i, weekday = %i) " ,str,date, dayDate, dayIndex);
return date;
}
This is the log
2013-06-05 => 2013-06-04 17:17:56 +0000 (date = 14, weekday = 3)
2013-06-06 => 2013-06-05 17:17:56 +0000 (date = 15, weekday = 4)
2013-06-07 => 2013-06-06 17:17:56 +0000 (date = 16, weekday = 5)
The NSDate shows that it is 4th of June, however the component
said the date is 14th.
Update - I tried the code on the simulator and it works fine, so the problem is with my iPhone 4.