2017-07-18 199 views
1

我有这样的日期格式.. 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];` 

但我无法得到小时和上午/下午值的权利。我怎样才能得到这个?

+0

什么是您的转换去错了。当你说你几个小时没有把握好时间,AM/PM你会得到什么样的价值? –

+0

我得到小时:最小值为10:51而不是15:51 – Boobalan

+0

尝试使用HH而不是hh – Himanth

回答

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年6月5日下午3点51

+0

谢谢@ Evgen.Its作品像一个魅力。感谢很多 – Boobalan

+0

对不起,这根本行不通。将输入时间更改为'@“2017-06-05T15:51:56.996-08:00”'(时区偏移量更改),并产生相同的最终结果。第二个产生'dateWithTZ'的代码块不用于确定'finalDateString'。 – CRD

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; 
} 
+0

它没有按预期工作。 – Boobalan

+0

这是正确的答案,@Boobalan为什么它不像你期望的那样工作? – CRD

+0

上述代码正在为此格式工作..“2016-11-28T14:57:30.000Z”而不是为此。“2017-06-05T15:51:56.996-07:00” – Boobalan