我试图从字符串中获取两个日期,因此代码如下:
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
我的错误是否存在?
答案 0 :(得分:1)
问题是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
,如上所示。