有人可以向我解释为什么以下代码会返回不一致的时间值吗?尝试从用户指定的日期/时间字符串创建NSDate对象时,我得到的结果不正确,并且我已将下面的代码放在一起以说明问题。
// Create two strings containing the current date and time
NSDateFormatter * dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];
NSDateFormatter * timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:@"HH:mm:ss a"];
timeFormat.AMSymbol = @"AM";
timeFormat.PMSymbol = @"PM";
timeFormat.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"EDT"];
NSDate * now = [[NSDate alloc] init];
NSString *theDate = [dateFormat stringFromDate:now];
NSString *theTime = [timeFormat stringFromDate:now];
NSLog(@"The current date/time is (GTM): %@", now);
NSLog(@"The current date/time is (EDT): %@ %@", theDate, theTime);
// Combine the date and time strings
NSMutableString * theDateTime = [[NSMutableString alloc] init];
theDateTime = [theDateTime stringByAppendingString:theDate];
theDateTime = [theDateTime stringByAppendingString:@" "];
theDateTime = [theDateTime stringByAppendingString:theTime];
// Define the formatter to parse the combined date and time string
NSDateFormatter * dateFormatter=[[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss a"];
dateFormatter.AMSymbol = @"AM";
dateFormatter.PMSymbol = @"PM";
dateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"EDT"];
// Create an NSDate object using the combined date and time string
NSDate * theDateTimeObject=[dateFormatter dateFromString:theDateTime];
NSString * theDateTimeString=[dateFormatter stringFromDate:theDateTimeObject];
// Print the results
NSLog(@"theDateTimeObject (GMT) = %@", theDateTimeObject);
NSLog(@"theDateTimeString (EDT) = %@", theDateTimeString);
此代码生成以下输出:
The current date/time is (GMT): 2015-09-29 22:28:10 +0000
The current date/time is (EDT): 2015-09-29 18:28:10 PM
theDateTimeObject (GMT) = 2015-09-29 16:28:10 +0000
theDateTimeString (EDT) = 2015-09-29 12:28:10 PM
显然,当日期格式化程序解析组合的日期和时间字符串以创建NSDate对象时,会出现问题。它似乎不理解输入时区,并返回GMT中的时间,该时间应该是几个小时(即+4小时)。我已经将时区设置为" EDT",所以不知道我还能做些什么来解决这个问题,除了硬编码输入中的偏移,我宁愿不做。任何帮助,将不胜感激。
答案 0 :(得分:2)
使用24小时格式(HH
)代替12小时格式(hh
)并使用AM / PM(a
),您做得很糟糕。
将格式中HH
的两个实例更改为hh
,您应该会得到预期的结果。
您还应将格式化程序的区域设置设置为特殊区域设置en_US_POSIX
,以避免设备的24小时时间设置出现问题。
附注:您对NSMutableString
的使用完全错误。试试这个:
NSMutableString * theDateTime = [[NSMutableString alloc] init];
[theDateTime appendString:theDate];
[theDateTime appendString:@" "];
[theDateTime appendString:theTime];
或只是使用:
NSString *theDateTime = [NSString stringWithFormat:@"%@ %@", theDate, theTime];