如何在Objective-C中增加NSDate对象 [英] How do I Increment an NSDate object in Objective-C

查看:53
本文介绍了如何在Objective-C中增加NSDate对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想输入当前日期作为第二天我使用的代码如下

I want to take the next day by giving the current date The code i used as follows

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

这可以正常工作,但是启用夏令时会导致错误.启用夏时制时,我该如何工作.

this works fine but when the daylight saving enabled this leads to errors. How can I make this work when daylight saving is enabled.

推荐答案

您已经发现,现在所拥有的内容很容易出错.它不仅会因夏令时变更而跳闸,而且如果您的用户使用非公历会怎样呢?然后,几天就不会24小时长了.

As you have found, what you have now is pretty error-prone. Not only can it trip up over a daylight savings change, but also what if your user has a non-gregorian calendar? Then, days are not 24 hours long.

相反,使用为此专门设计的 NSCalendar NSDateComponents :

Instead, use NSCalendar and NSDateComponents which were exactly designed for this:

+ (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];
}

这篇关于如何在Objective-C中增加NSDate对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆