基本上,就像标题说的那样。我想知道如何添加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)
其他回答
Swift 5.0:
var dayComponent = DateComponents()
dayComponent.day = 1 // For removing one day (yesterday): -1
let theCalendar = Calendar.current
let nextDate = theCalendar.date(byAdding: dayComponent, to: Date())
print("nextDate : \(nextDate)")
目标C:
NSDateComponents *dayComponent = [[NSDateComponents alloc] init];
dayComponent.day = 1;
NSCalendar *theCalendar = [NSCalendar currentCalendar];
NSDate *nextDate = [theCalendar dateByAddingComponents:dayComponent toDate:[NSDate date] options:0];
NSLog(@"nextDate: %@ ...", nextDate);
这应该是不言而喻的。
在swift中,您可以在NSDate中添加扩展方法
extension NSDate {
func addNoOfDays(noOfDays:Int) -> NSDate! {
let cal:NSCalendar = NSCalendar.currentCalendar()
cal.timeZone = NSTimeZone(abbreviation: "UTC")!
let comps:NSDateComponents = NSDateComponents()
comps.day = noOfDays
return cal.dateByAddingComponents(comps, toDate: self, options: nil)
}
}
你可以用这个
NSDate().addNoOfDays(3)
斯威夫特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”。
swift 5更新
let nextDate = fromDate.addingTimeInterval(60*60*24)
Swift 4.0(在这个精彩的答案中与Swift 3.0相同,只是为了让像我这样的新手清楚)
let today = Date()
let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: today)