0

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.

harinsa
  • 3,176
  • 5
  • 33
  • 53
  • I get the output `2013-06-05 => 2013-06-04 22:00:00 +0000 (date = 5, weekday = 4)` if I call your method with `2013-06-05`, and that is correct because I am at GMT+2. What timezone do you have? Is there anything else do did not show? – Martin R Jun 05 '13 at 18:03
  • I'm in GMT+7, the code works just hours ago, not sure if it might be because the time here just pass midnight? I don't really know how to work with the timezone in NSDate. – harinsa Jun 05 '13 at 18:06
  • @MartinR There is nothing else. That's the whole method. – harinsa Jun 05 '13 at 18:07

0 Answers0