1

谁能向我解释为什么以下代码返回不一致的时间值?尝试从用户指定的日期/时间字符串创建 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”,所以不确定我还能做些什么来解决这个问题,除了硬编码输入中的偏移量,我宁愿不这样做。任何帮助,将不胜感激。

4

1 回答 1

2

HH使用 24 小时格式 ( ) 而不是 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];
于 2015-09-29T23:14:52.417 回答