基本上,就像标题说的那样。我想知道如何添加1天的NSDate。
如果它是:
21st February 2011
它将变成:
22nd February 2011
或者如果它是:
31st December 2011
它将变成:
1st January 2012.
基本上,就像标题说的那样。我想知道如何添加1天的NSDate。
如果它是:
21st February 2011
它将变成:
22nd February 2011
或者如果它是:
31st December 2011
它将变成:
1st January 2012.
当前回答
swift 5更新
let nextDate = fromDate.addingTimeInterval(60*60*24)
其他回答
使用下面的函数,并使用days参数来获取日期daysAhead/daysBehind,只需将参数传递为正,表示未来日期,为负,表示之前日期:
+ (NSDate *) getDate:(NSDate *)fromDate daysAhead:(NSUInteger)days
{
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
dateComponents.day = days;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *previousDate = [calendar dateByAddingComponents:dateComponents
toDate:fromDate
options:0];
[dateComponents release];
return previousDate;
}
简单的Swift扩展昨天和明天从任何日期:
extension Date {
var previousDay: Date {
Calendar.current.date(byAdding: DateComponents(day:-1), to: self)!
}
var nextDay: Date {
Calendar.current.date(byAdding: DateComponents(day:+1), to: self)!
}
}
我在这里根据问题中的建议强制展开可选选项: 何时dateByAddingComponents:toDate:options返回nil?
斯威夫特2.0
let today = NSDate()
let calendar = NSCalendar.currentCalendar()
let tomorrow = calendar.dateByAddingUnit(.Day, value: 1, toDate: today, options: NSCalendarOptions.MatchFirst)
斯威夫特4.0
extension Date {
func add(_ unit: Calendar.Component, value: Int) -> Date? {
return Calendar.current.date(byAdding: unit, value: value, to: self)
}
}
使用
date.add(.day, 3)! // adds 3 days
date.add(.day, -14)! // subtracts 14 days
注意:如果你不知道为什么代码行以感叹号结尾,可以在谷歌上查找“Swift optional”。
它的工作原理!
NSCalendar *calendar = [NSCalendar currentCalendar];
NSCalendarUnit unit = NSCalendarUnitDay;
NSInteger value = 1;
NSDate *today = [NSDate date];
NSDate *tomorrow = [calendar dateByAddingUnit:unit value:value toDate:today options:NSCalendarMatchStrictly];