fhefh
V2EX  ›  iOS

iOS 开发, NSDate 与 NSString 转换相差 8 个小时问题

  •  
  •   fhefh · Sep 13, 2015 · 7048 views
    This topic created in 3919 days ago, the information mentioned may be changed or developed.

    服务器给的时间格式:
    "Sun Sep 13 11:43:04 +0800 2015"

    我的代码:

    NSString *timeString = @"Sun Sep 13 11:43:04 +0800 2015";

    NSTimeZone *sourceTimeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];

    NSDateFormatter *format = [[NSDateFormatter alloc] init];

    format.dateFormat = @"EEE MMM dd HH:mm:ss z yyyy";

    format.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];

    format.timeZone = sourceTimeZone;

    NSDate *date = [format dateFromString:timeString];

    NSLog (@"date: %@", date );

    打印结果:
    date: 2015-09-13 03:43:04 +0000

    相差了八个小时,昨晚到今天弄了好长时间都没有弄好~
    求指点~

    6 replies    2015-09-13 13:13:08 +08:00
    jianzong
        1
    jianzong  
       Sep 13, 2015
    不是 NSDate 与 NSString 转换的问题吧,字串跟打印结果的时区就是差了 8 小时。

    后面的+0000 和+0800 是指时区。
    painter
        2
    painter  
       Sep 13, 2015
    @jianzong 对 是因为时区的原因 不是转换的问题
    wezzard
        3
    wezzard  
       Sep 13, 2015
    結果是正確的,一個是 GMT +8 一個是 UTC ,兩個時間是相等的。

    你可以嘗試一下用兩個 NSDateFormatter ,一個用來完成 NSString -> NSDate 的轉換,一個用來完成 NSDate -> NSString 的轉換,第一個 NSDateFormatter 不要設置時區,因爲你的 date format 裏面已經提示了時區,第二個 NSDateFormatter 設置時區爲本地時區。
    SeanChense
        4
    SeanChense  
       Sep 13, 2015 via iPhone
    中国在东八区。
    fhefh
        5
    fhefh  
    OP
       Sep 13, 2015
    NSString *timeString = @"Sun Sep 13 11:43:04 +0800 2015";

    NSTimeZone *sourceTimeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];

    NSDateFormatter *format = [[NSDateFormatter alloc] init];

    format.dateFormat = @"EEE MMM dd HH:mm:ss z yyyy";

    format.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];

    format.timeZone = sourceTimeZone;

    NSDate *date = [format dateFromString:timeString];

    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:date];
    NSDate *localDate = [date dateByAddingTimeInterval:interval];

    NSLog (@"date: %@", localDate );

    已解决~ 3QS

    参考: http://blog.csdn.net/diyagoanyhacker/article/details/7096612
    zerh925
        6
    zerh925  
       Sep 13, 2015 via iPhone
    format.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    @“ en_US ”是美国?
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   883 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 22:28 · PVG 06:28 · LAX 15:28 · JFK 18:28
    ♥ Do have faith in what you're doing.