【问题标题】:NSDate is not converting correctly using NSDateFormatterNSDate 没有使用 NSDateFormatter 正确转换
【发布时间】:2011-06-11 21:18:06
【问题描述】:

我有以下 NSDateFormatter:

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MMM. d, yyyy"];

NSLocale *usLocal = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[dateFormatter setLocale:usLocal];

我有一个 while 循环,它从给定的开始日期开始,并将日期加一,直到达到特定的结束日期。

NSDate *d = start;
while(YES){     
   NSString *td = [dateFormatter stringFromDate:d];
   NSLog(@"converted date %@ to %@",d,td);
   ...adds a date and re-initializes d
}

我得到如下输出:

2011-06-11 17:10:18.678 ListOf100[8784:707] converted date 2011-05-31 00:00:00 +0000 to May. 30, 2011
2011-06-11 17:10:18.687 ListOf100[8784:707] converted date 2011-06-01 00:00:00 +0000 to May. 31, 2011
2011-06-11 17:10:18.717 ListOf100[8784:707] converted date 2011-06-02 00:00:00 +0000 to Jun. 1, 2011

如您所见,所有日期都没有正确转换。他们都休息了 1 天。为什么会发生这种情况?我该如何解决?

【问题讨论】:

  • 你能发布你如何重新初始化“d”吗?
  • 这不是问题。即使是第一次也是错误的。
  • 您应该向 Apple 报告此错误。我同意@Sai,您应该发布代码,以便我们测试它是否可重现。

标签: ios nsdate nsdateformatter


【解决方案1】:

在我看来,日期创建的时区与格式化程序所在的时区不同。

NSDate * d = [NSDate dateWithTimeIntervalSince1970:800000];    
// Arbitrary date

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MMM. d, yyyy"];

NSLocale *usLocal = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[dateFormatter setLocale:usLocal];


//!!!: Set time zone
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

NSString *td = [dateFormatter stringFromDate:d];
NSLog(@"converted date %@ to %@",d,td);

产量:

2011-06-11 22:44:01.642 TimeZoneFormatter[21901:207] 将日期 1970-01-10 06:13:20 +0000 转换为 1970 年 1 月 10 日

【讨论】:

    【解决方案2】:

    不知道为什么会这样,但如果它是持久的,那么修复它应该不会比在转换之前为 d 添加一天更难:

    NSString *td = [dateFormatter stringFromDate:[d dateByAddingTimeInterval:86400]];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多