如何在 Objective-C 中递增 NSDate 对象
-
11-09-2019 - |
题
我想第二天通过给当前日期使用我使用的代码如下
+(NSDate *)getForDays:(int)days fromDate:(NSDate *) date {
NSTimeInterval secondsPerDay = 24 * 60 * 60 * days;
return [date addTimeInterval:secondsPerDay];
}
这工作正常,但当启用夏令时时,这会导致错误。当启用夏令时时,我怎样才能做到这一点?
解决方案
当你发现,你现在有什么是很容易出错。它不仅可以绊倒在夏令时的变化,但也如果你的用户具有非阳历?然后,天都没有在24小时长。
相反,使用NSCalendar
和NSDateComponents
其被精确地设计为这样的:
+ (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];
}
不隶属于 StackOverflow