【问题标题】:Incorrect output from NSDateFormatterNSDateFormatter 的输出不正确
【发布时间】:2012-09-16 02:42:05
【问题描述】:

我从 NSDateFormatter 得到一些奇怪的输出。我正在将日期从 GMT 转换为系统时区,即 EDT。这应该是格林威治标准时间 -4 小时。

-(NSDate*)parseDate:(NSString*)inStrDate {

NSLog(@"Date To Parse %@", inStrDate);
NSDateFormatter* dtFormatter = [[NSDateFormatter alloc] init];
[dtFormatter setLocale:[NSLocale systemLocale]];
[dtFormatter setTimeZone:[NSTimeZone systemTimeZone]];
[dtFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss +0000"];
NSDate* dateOutput = [dtFormatter dateFromString:inStrDate];
NSLog(@"Parsed Date %@ %@", dateOutput, [NSTimeZone systemTimeZone]);

return dateOutput;

}

日志输出:

2012-09-15 22:32:53.358 解析日期 2012-09-16 02:32:53 +0000 2012-09-15 22:32:53.360 解析日期 2012-09-16 06:32:53 +0000 America/New_York (EDT) offset -14400 (Daylight)

但它返回 +4 小时而不是 -4 小时。所以它应该输出 22.30 EDT(格林威治标准时间 02.30)它实际上返回 06.30 EDT。也就是未来 8 小时。

任何人都可以帮助我了解我是否在这里的某个地方出错了?我在挠头,但我不明白为什么这似乎不起作用。

谢谢

【问题讨论】:

    标签: ios nsdateformatter


    【解决方案1】:

    您只是弄错了 dateFormatter。 当你这样做时

    [dtFormatter setTimeZone:[NSTimeZone systemTimeZone]];
    

    您是在告诉它,输入日期是根据您的时区。因此,它将其转换为 GMT 并输出时间 +4 小时。反过来,你可以使用这个:

    NSDateFormatter* df_local = [[NSDateFormatter alloc] init];
    [df_local setTimeZone:[NSTimeZone timeZoneWithName:@"America/New_York"]];
    [df_local setDateFormat:@"yyyy.MM.dd' 'HH:mm:ss zzz"];
    
    NSDate* dateOutput = [dtFormatter dateFromString:dateString];
    NSLog(@"Parsed Date in GMT %@", dateOutput);
    NSString *yourLocalDate = [df_local stringFromDate:dateOutput];
    NSLog(@"in EDT %@",yourLocalDate);
    

    此日志

    2012-09-16 05:23:53.297 TestingApplication[10109:c07] Date To Parse 2012-09-16 02:32:53 +0000
    2012-09-16 05:23:53.302 TestingApplication[10109:c07] Parsed Date in GMT 2012-09-16 02:32:53 +0000
    2012-09-16 05:23:53.304 TestingApplication[10109:c07] in EDT 2012.09.15 22:32:53 EDT
    

    【讨论】:

      【解决方案2】:

      如果您想要一个日期作为最终输出,您可以跳过辅助 NSDateFormatter 并只需“添加”UTC 日期和本地时间之间的差异。

      formatter = [[NSDateFormatter alloc] init];
      [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];        
      [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
      NSDate *date = [formatter dateFromString:dateString]; // UTC date
      NSDate *date2 = [date dateByAddingTimeInterval:[[NSTimeZone localTimeZone] secondsFromGMTForDate:date]]; // local date!
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-05-11
        • 2013-07-27
        • 2015-10-30
        • 1970-01-01
        • 1970-01-01
        • 2015-09-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多