2017-07-18 4 views
1

私はこのような日付形式を持っています。2017-06-05T15:51:56.996-07:00yyyy-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

私は時間を得ています:15:51の代わりに10: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 PM

+0

Thanks @ Evgen.Its魅力のように動作します。ありがとうございます – Boobalan

+0

申し訳ありませんが、これはうまくいきません。入力時間を '@" 2017-06-05T15:51:56.996-08:00 "(タイムゾーンオフセットの変更)に変更し、同じ最終結果を生成します。 'dateWithTZ'をもたらすコードの2番目のブロックも' 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

関連する問題