NSDateFormatter 广告 10 小时?

NSDateFormatter adds 10hours?

我想从字符串中获取两个日期,所以代码如下:

         NSString *serverDateString     = array[0];
         NSString *nextEventDateString  = array[1];
         NSDateFormatter *dateFormatter = [NSDateFormatter new];
         [dateFormatter setDateFormat:@"hh:mm dd.MM.yyyy"];

         timer.serverTime           = [dateFormatter dateFromString:serverDateString];
         timer.nextEventTime        = [dateFormatter dateFromString:nextEventDateString];

但我得到的是:

(lldb) po serverDateString
12:15 16.03.2015

(lldb) po nextEventDateString
00:00 17.03.2015

(lldb) po timer.serverTime
2015-03-15 22:15:00 +0000

(lldb) po timer.nextEventTime
2015-03-16 22:00:00 +0000

有没有我的错误?

问题是 dateFromString: 取决于您 NSDateFormatter 的时区。所以你需要告诉你的格式化程序,使用哪个时区:

NSString *serverDateString     = array[0];
NSString *nextEventDateString  = array[1];

NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setDateFormat:@"hh:mm dd.MM.yyyy"];

// Set the time zone here
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"CET"]];

// If not sure, this will give you a list of abbreviations
// NSLog(@"%@", [NSTimeZone abbreviationDictionary]);

timer.serverTime           = [dateFormatter dateFromString:serverDateString];
timer.nextEventTime        = [dateFormatter dateFromString:nextEventDateString];

如果您不确定可以使用的时区缩写,可以使用 NSTimeZone abbreviationDictionary,如上所示。