NSDate不能正确转换使用NSDateFormatter

我有以下NSDateFormatter:

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"MMM. d, yyyy"]; NSLocale *usLocal = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]; [dateFormatter setLocale:usLocal]; 

我有一个while循环,从给定的开始date开始,将date递增1,直到到达特定的结束date。

 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 

正如你所看到的,所有的date都不能正确转换。 他们都rest了一天。 为什么会这样呢? 我该如何解决?

看起来像date正在创build在不同的时区,格式化的工作。

 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]转换date1970-01-10 06:13:20 +0000至1970年1月10日

不知道它为什么会发生,但如果它是持久的,修改它不应该比转换之前添加一天更难:

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