Search code examples
iosobjective-cnsstringnsdatensdateformatter

Converting date format


I have date format like this .. 2017-06-05T15:51:56.996-07:00 and I need to convert it to yyyy-MM-dd hh:mm a . I am using the following code.

NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZZZZ"];
NSDate *date = [format dateFromString:dateString];
[format setDateFormat:@"yyyy-MM-dd hh:mm a"];
NSString* finalDateString = [format stringFromDate:date];`

But I couldn't get the hours and AM/PM values right. How can I get this?


Solution

  • NSString *dateStringWithTZ = @"2017-06-05T15:51:56.996-07:00";
    
    // Create date object using the timezone from the input string.
    NSDateFormatter *dateFormatterWithTZ = [[NSDateFormatter alloc] init];
    dateFormatterWithTZ.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSSZ";
    NSDate *dateWithTZ = [dateFormatterWithTZ dateFromString:dateStringWithTZ];
    
    // Cut off the timezone and create date object using GMT timezone.
    NSString *dateStringWithoutTZ = [dateStringWithTZ substringWithRange:NSMakeRange(0, 23)];
    NSDateFormatter *dateFormatterWithoutTZ = [[NSDateFormatter alloc] init];
    dateFormatterWithoutTZ.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSS";
    dateFormatterWithoutTZ.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
    NSDate *dateWithoutTZ = [dateFormatterWithoutTZ dateFromString:dateStringWithoutTZ];
    
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    [format setDateFormat:@"yyyy-MM-dd hh:mm a"];
    [format setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
    format.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
    NSString* finalDateString = [format stringFromDate:dateWithoutTZ];
    

    RESULT: 2017-06-05 03:51 PM