Converting NSString to NSDate - wrong format

2019-02-20 09:06发布

问题:

Hi I am trying to convert a string into NSDate format - but it returns value with wrong format and also in GMT time.

 NSString *myString = @"10:30 AM";
 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
 NSTimeZone *local = [NSTimeZone systemTimeZone];
 dateFormatter.dateFormat = @"hh:mm a";
[dateFormatter setTimeZone:local];
 NSDate *myDate = [dateFormatter dateFromString:myString];



NSLog(@"myDate---%@",myDate);

But this returns

  myDate---2000-01-01 05:30:00 +0000

Where I am making the mistake, what to do to get the date as 10:30 AM, Please help me to fix this. Thanks in advance

回答1:

Don't use NSLog() to display the date as that will format it using the UTC/GMT timezone and its own format; instead use the date formatter to display it:

NSLog(@"myDate---%@", [dateFormatter stringFromDate:myDate]);