Search code examples
iosnsdatensdateformatter

There is differnce in date while I convert string to date


I am using following code to get date from string. All seems to be good in code but while I print the output date, there is difference of 12:30 hours in date.

What may be the issue? Am I missing something ?

NSString *strDate = @"8/22/2017 7:00:00 AM";
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"MM/dd/yyyy HH:mm:ss a"];
NSDate *date = [df dateFromString:strDate];
NSLog(@"%@", [date description]);

Output:

2017-08-21 18:30:00 +0000


Solution

  • The hour specifier is wrong, 12 hour format is hh

    [df setDateFormat:@"MM/dd/yyyy hh:mm:ss a"];
    

    Note:

    Be aware that NSLog prints the date always in UTC although the date formatter considers the local time zone.