【问题标题】:NSDate loses and hour when adding a month during DST change?在 DST 更改期间添加一个月时,NSDate 会丢失和小时?
【发布时间】:2015-02-02 08:51:49
【问题描述】:

当尝试在我能找到的所有 stackoverflow 问题上使用建议的“正确”方法添加一个月时,由于 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-29 00:00:00 +0000

新日期: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];
}

【问题讨论】:

    标签: ios objective-c iphone nsdate


    【解决方案1】:

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

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

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

    【讨论】:

    • 因此,没有明显的方法可以在一年中不断增加,同时保持时间在午夜。例如,如果有人想在每个月的午夜从原始日期设置重复日历事件?请参阅上面的问题编辑示例。
    • 在我上面添加的示例中,前两个日期设置为午夜,后两个日期设置为 23:00。将它们全部设置为所需的午夜时间的最佳解决方案是什么?
    • 23:00 午夜。想象一下,您正坐在纽约并运行您的代码。纽约时间比世界标准时间晚五个小时。因此,纽约的午夜是 UTC 时间早上 5:00。在伦敦,冬季的午夜是凌晨 0:00,而在春季,当您将时钟拨快时,午夜是下午 23:00。
    • 我理解您对使用 UTC 作为参考点的 NSDate 的意思。但可以肯定的是,如果他们要努力返回本地时间,包括世界各地的 DST 计算,他们还将包括一种从设定时间的一天转换到同一设定时间的第二天的方法,以考虑任何变化由于夏令时。从用户的角度来看,当他们提到春季或冬季的午夜时,他们指的是当前当地时间的上午 00:00?
    • NSLog 显示 UTC。正如我从一开始就说的那样,您得到的结果是正确的
    猜你喜欢
    • 1970-01-01
    • 2019-10-14
    • 2014-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多