How do I Increment an NSDate object in Objective-C

自闭症网瘾萝莉.ら 提交于 2020-01-03 10:19:26

问题


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.


回答1:


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.

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



回答2:


Use NSCalendar to perform calculations like this. Not only is it more likely to work, but your code will be clearer.




回答3:


I've no idea what language or system you're using here, but my advice would be to perform all of your calculations using time as UTC and only use local time when you come to display it.

Most operating systems and languages will factor in timzone and daylight saving on the conversion of UTC to local time.



来源:https://stackoverflow.com/questions/1091113/how-do-i-increment-an-nsdate-object-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!