2017-07-18 196 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