[英]NSDate is not converting correctly using NSDateFormatter
我有以下 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
}
我得到 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
如您所見,所有日期都沒有正確轉換。 他們都休息了 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 日
不知道它為什么會發生,但如果它是持久的,修復它應該不會比在轉換之前在 d 中添加一天更難:
NSString *td = [dateFormatter stringFromDate:[d dateByAddingTimeInterval:86400]];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.