NSDateFormatter 返回意外的时间值

NSDateFormatter Returning Unexpected Time Values

谁能给我解释一下为什么下面的代码 returns 时间值不一致?在尝试从用户指定的 date/time 字符串创建 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 对象时,显然出了点问题。它似乎不理解输入的时区和 returns 格林威治标准时间的时间比应该的时间晚几个小时(即 +4 小时)。我已将时区设置为 "EDT",所以不确定我还能做些什么来解决这个问题,除了硬编码输入中的偏移量,我宁愿不这样做。任何帮助,将不胜感激。

您使用 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];