简体   繁体   English

NSDate 没有使用 NSDateFormatter 正确转换

[英]NSDate is not converting correctly using NSDateFormatter

I have the following NSDateFormatter:我有以下 NSDateFormatter:

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

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

and I have a while loop which starts at a given start date and increments the date by one until it reaches a specific end date.我有一个while循环,它从给定的开始日期开始,并将日期加一,直到达到特定的结束日期。

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

And I'm getting output such as the following:我得到 output 如下:

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

As you can see, all the dates are not converting properly.如您所见,所有日期都没有正确转换。 They are all off by 1 day.他们都休息了 1 天。 Why could this be happening?为什么会发生这种情况? And how can I fix it?我该如何解决?

Looks to me like the dates are being created in a different time zone than the one the formatter's working in.在我看来,日期是在与格式化程序工作的时区不同的时区创建的。

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);

Yields:产量:

2011-06-11 22:44:01.642 TimeZoneFormatter[21901:207] converted date 1970-01-10 06:13:20 +0000 to Jan. 10, 1970 2011-06-11 22:44:01.642 TimeZoneFormatter[21901:207] 转换日期 1970-01-10 06:13:20 +0000 到 1970 年 1 月 10 日

Don't know why it's happening, but if it's persistent, fixing it shouldn't be harder than adding a day to d before converting it:不知道它为什么会发生,但如果它是持久的,修复它应该不会比在转换之前在 d 中添加一天更难:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM