2016-11-21 13 views
0

私は奇妙な結果をNSDateオブジェクトのNSStringから出力しようとしました。 私NSStringは次のとおりです。変換する1976年6月11日 私の方法は次のとおりです。NSStringからNSDateへの奇妙な変換出力

-(NSDate*)dateFromString:(NSString *)dateString{ 

    // Convert string to date object 
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
    [dateFormat setDateFormat:@"yyyy-MM-dd"]; 
    NSDate *date = [dateFormat dateFromString:dateString]; 
    return date; 
} 

しかし、出力1976-06-10 21:00:00 +0000

どのようにそれが起こるのだろうか? 1日の違い。

+0

このような出力のためにdateStringは何ですか? –

+0

タイムゾーンの問題。 NSDateFormatterにタイムゾーンを与えてみてください –

+1

違いは3時間で、1日ではありません。あなたのタイムゾーンはUTC + 3ですね。 'NSLog'は常に日付をUTCで表示しますが、日付は正しいです。 – vadian

答えて

1

あなたはUTCの日付とローカルの日付

- (NSDate *)convertIntoGMTZoneDate:(NSString *)dateString 
    { 
     NSDateFormatter *gmtFormatter = [[NSDateFormatter alloc]init]; 
     [gmtFormatter setDateStyle:NSDateFormatterFullStyle]; 
     [gmtFormatter setTimeStyle:NSDateFormatterFullStyle]; 
     [gmtFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]]; 

     return [gmtFormatter dateFromString:dateString]; 
    } 

    - (NSDate *)convertIntoSystemZoneDate:(NSString *)dateString 
    { 
     NSDateFormatter *systemZoneFormatter = [[NSDateFormatter alloc]init]; 
     [systemZoneFormatter setDateStyle:NSDateFormatterFullStyle]; 
     [systemZoneFormatter setTimeStyle:NSDateFormatterFullStyle]; 
     [systemZoneFormatter setTimeZone:[NSTimeZone systemTimeZone]]; 

     return [systemZoneFormatter dateFromString:dateString]; 
    } 
2

UTC形式の日付です。現地時間にあなたの日付を変換するには、このコードを使用します。

NSTimeInterval seconds; // assume this exists 
NSDate *ts_utc = [NSDate dateWithTimeIntervalSince1970:seconds]; 

NSDateFormatter *utcFormatter = [[NSDateFormatter alloc] init]; 
utcFormatter.timeZone = [NSTimeZone timeZoneWithName:@"UTC"]; 
utcFormatter.dateFormat = @"yyyy.MM.dd G 'at' HH:mm:ss zzz"; 

NSDateFormatter *localFormatter = [[NSDateFormatter alloc] init]; 
localFormatter.timeZone = [NSTimeZone timeZoneWithName:@"EST"]; 
localFormatter.dateFormat = @"yyyy.MM.dd G 'at' HH:mm:ss zzz"; 

NSString *utcDateString = [utcFormatter stringFromDate:ts_utc]; 
NSString *LocalDateString = [localFormatter stringFromDate:ts_utc]; 

それとも、タイムゾーン名のハードコードされた文字列を防ぐために[NSTimeZone defaultTimeZone]を使用することができます。このメソッドは、デフォルトのタイムゾーンが設定されていない場合、システムのタイムゾーンを返します。

1
func dateFromString(dateString: String) -> NSDate { 
    // Convert string to date object 
    var dateFormat = NSDateFormatter() 
    dateFormat.dateFormat = "yyyy-MM-dd" 
    dateFormat.timeZone = NSTimeZone(name: "UTC") 
    var date = dateFormat.dateFromString(dateString)! 
    print(date) 
    return date 
} 

出力: 1976年6月11日夜12時00分○○秒0000

+0

ありがとうございますが速くはありません。 –

+1

代わりにこれを使用してください [dateFormat setTimeZone:[NSTimeZone timeZoneWithName:@ "UTC"]]; – rvx

1

にUTCの日付文字列を変換するには、次の方法を使用することができますコードをデバッグすると、1日の差異が表示されますが、実行後に入力した実際の日付が表示されます。

それは私のために働く。私はそれがあなたを助けると思う。 ありがとうございます