0

想知道我是否发现了 NSDateComponents 的错误。

使用 NSDateComponents 计算日期并在时区之间切换时,可能会在模拟器上得到错误的日期(未在设备上测试)。

似乎它是正确的偏移量,但方向错误。要么,要么我从根本上误解了某些东西(这总是一种明显的可能性)。

样本:

将系统时间设置为 UTC 以外的时区(我的是墨西哥,UTC-05:00)

// Get the components for the current absolute time.
NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSYearCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit | NSMinuteCalendarUnit | NSHourCalendarUnit | NSSecondCalendarUnit) fromDate:[NSDate date]];

// Get the calendar, which seems to set the time zone to the current time zone
components.calendar = [NSCalendar currentCalendar];
// Set the time zone to UTC
components.calendar.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];

// Log the date
NSLog(@"Date at time zone: %@ : %@", components.calendar.timeZone, [components date]);
// Outputs (e.g): "Date at time zone: GMT (GMT) offset 0 : 2013-06-21 14:55:56 +0000"
// This should be absolute time, so any changes in the time zone should offset
// relative to this.

// Set the time zone to the local time zone (e.g. Mexico, 5 hours behind)
components.calendar.timeZone = [NSTimeZone localTimeZone];
// Log the date
NSLog(@"Date at time zone: %@ : %@", components.calendar.timeZone, [components date]);
// Outputs (e.g.): "Date at time zone: Local Time Zone (America/Mexico_City (CDT) offset -18000 (Daylight)) :2013-06-21 19:55:56 +0000"

假设墨西哥,第二个日期不应该比第一个晚五个小时吗?

4

1 回答 1

0

设置components.calendar.timeZone为墨西哥时区后,components 代表(在您的示例中)

2013-06-21 14:55:56 in the Mexican time zone

因此[components date]返回NSDate那个时间点的一个。

NSLog输出使用 , 的方法descriptionNSDate并且总是在 GMT 时区打印时间点,即

2013-06-21 19:55:56 +0000

所以对我来说一切都很好。

于 2013-06-21T20:31:44.523 回答