我想第二天通过给当前日期使用我使用的代码如下

+(NSDate *)getForDays:(int)days fromDate:(NSDate *) date {
    NSTimeInterval secondsPerDay = 24 * 60 * 60 * days;
        return [date addTimeInterval:secondsPerDay];
} 

这工作正常,但当启用夏令时时,这会导致错误。当启用夏令时时,我怎样才能做到这一点?

有帮助吗?

解决方案

当你发现,你现在有什么是很容易出错。它不仅可以绊倒在夏令时的变化,但也如果你的用户具有非阳历?然后,天都没有在24小时长。

相反,使用NSCalendarNSDateComponents其被精确地设计为这样的:

+ (NSDate *)getForDays:(int)days fromDate:(NSDate *)date
{
    NSDateComponents *components= [[NSDateComponents alloc] init];
    [components setDay:days];

    NSCalendar *calendar = [NSCalendar currentCalendar];
    return [calendar dateByAddingComponents:components toDate:date options:0];
}

其他提示

使用 NS日历 去表演 像这样的计算. 。它不仅更有可能工作,而且你的代码也会更清晰。

我不知道你所使用的语言或系统在这里,但我的建议是执行所有使用时间为UTC您的计算,只有当你来显示它使用本地时间。

大多数操作系统和语言将在timzone和夏令上UTC的本地时间的转换因子。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top