V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
fhefh
V2EX  ›  iOS

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

  •  
  •   fhefh · 2015-09-13 12:12:31 +08:00 · 6441 次点击
    这是一个创建于 3173 天前的主题,其中的信息可能已经有所发展或是发生改变。

    服务器给的时间格式:
    "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 条回复    2015-09-13 13:13:08 +08:00
    jianzong
        1
    jianzong  
       2015-09-13 12:19:53 +08:00
    不是 NSDate 与 NSString 转换的问题吧,字串跟打印结果的时区就是差了 8 小时。

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

    你可以嘗試一下用兩個 NSDateFormatter ,一個用來完成 NSString -> NSDate 的轉換,一個用來完成 NSDate -> NSString 的轉換,第一個 NSDateFormatter 不要設置時區,因爲你的 date format 裏面已經提示了時區,第二個 NSDateFormatter 設置時區爲本地時區。
    SeanChense
        4
    SeanChense  
       2015-09-13 12:35:50 +08:00 via iPhone
    中国在东八区。
    fhefh
        5
    fhefh  
    OP
       2015-09-13 12:50:06 +08:00
    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  
       2015-09-13 13:13:08 +08:00 via iPhone
    format.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    @“ en_US ”是美国?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2131 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 16:10 · PVG 00:10 · LAX 09:10 · JFK 12:10
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.