在 DST 更改期间添加一个月时 NSDate 丢失和小时?

NSDate loses and hour when adding a month during DST change?

当尝试使用建议的 'correct' 方法对我能找到的所有 Whosebug 问题添加一个月时,由于 DST,我返回的日期总是损失一个小时。

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

NSDateComponents *component = [[NSDateComponents alloc] init];
[component setDay:29];
[component setMonth:3];
[component setYear:2015];
NSDate *date = [gregorian dateFromComponents:component];
NSLog(@"Date: %@", date);

NSDateComponents *monthComponent = [[NSDateComponents alloc] init];
monthComponent.month = 1;

NSDate *newDate = [gregorian dateByAddingComponents:monthComponent toDate:date options:0];

NSLog(@"newDate: %@", newDate);

这段代码的输出是:

日期:2015-03-2900:00:00+0000

newDate: 2015-04-28 23:00:00 +0000

如何在 DST 更改中添加一个月并将时间保持在午夜?

感谢您的帮助。

以下响应 gnasher729 的示例:

在示例中,前两个日期设置为午夜,后两个设置为 23:00。在将所有输出日期保持在所需的午夜时间的同时,实施此类操作的最佳做​​法是什么?

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

NSDateComponents *initialDateComponent = [[NSDateComponents alloc] init];
[initialDateComponent setDay:29];
[initialDateComponent setMonth:1];
[initialDateComponent setYear:2015];
NSDate *date = [gregorian initialDateComponent];
NSLog(@"Date: %@", date);

NSDateComponents *monthComponent = [[NSDateComponents alloc] init];
monthComponent.month = 1;
monthComponent.hour = 0;
NSMutableArray *eventAlarmDate = [[NSMutableArray alloc] init];

int numberOfRepeatingMonths = 4;
for(int x = 0; 0 < numberOfRepeatingMonths; x++) {
   date = [gregorian dateByAddingComponents:monthComponent toDate:date options:0];
  [eventAlarmDate addObject:date];
}

您实际上是在问我们如何在您的代码中引入错误。

结果正确。在 DST 更改期间增加一个月将并且必须比全天增加一小时或减少一小时。

NSDate always 以 UTC 显示日期,这是英国时间,没有 DST 校正。计算的日期是 DST 更正,这取决于您所在的位置。如果您在印度,则午夜是世界标准时间上午 5:30(或前一天世界标准时间下午 18:30,不确定)。