Search code examples
iosobjective-cnsdatensdateformatternstimezone

Convert NSString to NSDate with am/pm and timezone


My input NSString is 2017-01-11 5:33:55 am +0000. And my codes are:

    date = @"2017-01-11 5:33:55 am +0000";
    uploadFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss a Z";
    [uploadFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
    NSDate *theDate = [uploadFormatter dateFromString:date];

But the returned NSDate are always 2017-01-11 0:33:55 UTC regardless of the input hour. It means if input is 2017-01-11 3:33:55 am +0000, the result is also the same.

Does anyone has encounter the problem before? Any idea will be appreciated.


Solution

  • HH is four hour in 24h format, but since you have "am"/"pm", it's clearly 12h format. Change HH with hh in your dateFormat.

    Keep in mind the doc available here for the format, which for iOS7+ is here.