我正在尝试通过循环以下代码在每 2 周的 12:00(中午)安排通知...
unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit;
// Allocate new temporary calendar object with default timezone
NSCalendar *tmpCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[tmpCalendar setTimeZone:[NSTimeZone defaultTimeZone]];
// Allocate new temporary date components from the date to fire
NSDateComponents *tmpDateComps = [tmpCalendar components:unitFlags fromDate:dateToFire];
// Set time to '12.00'
[tmpDateComps setHour:12];
[tmpDateComps setMinute:0];
// Get new date to fire object based on date components
dateToFire = [tmpCalendar dateFromComponents:tmpDateComps];
NSLog(@"dateToFire %@", dateToFire);
// On 6th iteration = xx-xx-xxxx 09:00 +00:00
// On 11th iteration = xx-xx-xxxx 10:00 +00:00
// Allocate new temporary offset date components
NSDateComponents *tmpOffsetComps = [[NSDateComponents alloc] init];
// Add a number of weeks
[tmpOffsetComps setWeek:2];
// Get new date to fire object based on offset date components
dateToFire = [tmpCalendar dateByAddingComponents:tmpOffsetComps toDate:dateToFire options:0];
NSLog(@"dateToFire %@", dateToFire);
//On 6th iteration = xx-xx-xxxx 10:00 +00:00
//On 11th iteration = xx-xx-xxxx 09:00 +00:00
不知何故,当我dateToFire
在循环中记录对象时,在第 6 次迭代中,我首先得到了正确的结果xx-xx-xxxx 09:00 +00:00
,但是在添加了偏移组件之后的第二个日志中,我得到了xx-xx-xxxx 10:00 +00:00
. 奇怪的是它在第 11 次迭代中恢复到正确的时间。
我做错了什么以及如何解决这种奇怪的行为?
更新
正如 UIAdam 所说,这是由于夏令时而发生的,所以这是正常行为。