转换日期格式

时间:2017-07-18 11:24:32

标签: ios objective-c nsstring nsdate nsdateformatter

我有这样的日期格式.. 2017-06-05T15:51:56.996-07:00我需要将其转换为yyyy-MM-dd hh:mm a。我使用以下代码。

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];`

但我无法获得正确的时间和AM / PM值。我怎么能得到这个?

2 个答案:

答案 0 :(得分:2)

需要设置日历区域如下:

-(NSString *)DateToString:(NSString *)getString
{

    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    [format setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZZZZ"];
    NSDate *date = [format dateFromString:getString];
    [format setDateFormat:@"yyyy-MM-dd hh:mm a"];
    [format setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
    NSString* finalDateString = [format stringFromDate:date];
    return finalDateString;
}

答案 1 :(得分:1)

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];

结果:2017-06-05 03:51 PM