基本上,就像标题说的那样。我想知道如何添加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 4,如果你真正需要的是24小时轮班(60*60*24秒)而不是“1个日历天”
未来: let dayAhead = Date(timeIntervalSinceNow: TimeInterval(86400.0))
过去: let dayAgo = Date(timeIntervalSinceNow: TimeInterval(-86400.0))
其他回答
斯威夫特5
let today = Date()
let nextDate = Calendar.current.date(byAdding: .day, value: 1, to: today)
objective - c
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
// now build a NSDate object for the next day
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setDay:1];
NSDate *nextDate = [gregorian dateByAddingComponents:offsetComponents toDate: [NSDate date] options:0];
你可以使用NSDate的方法- (id)dateByAddingTimeInterval:(NSTimeInterval)秒,其中秒为60 * 60 * 24 = 86400
斯威夫特2.0
let today = NSDate()
let calendar = NSCalendar.currentCalendar()
let tomorrow = calendar.dateByAddingUnit(.Day, value: 1, toDate: today, options: NSCalendarOptions.MatchFirst)
iOS 8+, OSX 10.9+, Objective-C
NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *tomorrow = [cal dateByAddingUnit:NSCalendarUnitDay
value:1
toDate:[NSDate date]
options:0];
在Swift 4或Swift 5中,你可以使用like bellow:
let date = Date()
let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: date)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let yesterday_date = dateFormatter.string(from: yesterday!)
print("yesterday->",yesterday_date)
输出:
Current date: 2020-03-02
yesterday date: 2020-03-01