-1

Why does the below code output the incorrect Date after conversion?

NSString *customDate = @"23-06-1993";
NSLog(@"Custom Date: %@", customDate);
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd-MM-yyyy"];
NSDate *birthDayDate = [formatter dateFromString:customDate];
NSLog(@"After Conversion: %@", birthDayDate);

Output:

Custom Date: 20-12-1993
After Conversion: 1993-12-19 16:00:00 +0000

Thanks in advance.

Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119
user2771150
  • 722
  • 4
  • 10
  • 33

1 Answers1

-4

NSDateFormatter uses your current timezone (GMT+8) unless you explicitly set. You should set your formatter's timezone as UTC (in other words GMT) to format your date correctly.

NSLog(@"Current timezone: %@", [NSTimeZone defaultTimeZone]);

NSString *customDate = @"23-06-1993";
NSLog(@"Custom Date: %@", customDate);

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd-MM-yyyy"];
[formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];

NSDate *utcDate = [formatter dateFromString:customDate];
NSLog(@"After Conversion: %@", utcDate);

Custom Date: 23-06-1993
After Conversion: 1993-06-23 00:00:00 +0000
Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119
  • 3
    This is just wrong. Changing the timezone to UTC will change the actual date, with the side effect that the date now looks correct when printed via `[date description]`. – Matthias Bauch Mar 10 '15 at 07:19