基本上,就像标题说的那样。我想知道如何添加1天的NSDate。

如果它是:

21st February 2011

它将变成:

22nd February 2011

或者如果它是:

31st December 2011

它将变成:

1st January 2012.

当前回答

它的工作原理!

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

其他回答

Swift 4更新:

let now = Date() // the current date/time
let oneDayFromNow = Calendar.current.date(byAdding: .day, value: 1, to: now) // Tomorrow with same time of day as now

swift 5更新

let nextDate = fromDate.addingTimeInterval(60*60*24)

简单的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?

iOS 8+, OSX 10.9+, Objective-C

NSCalendar *cal = [NSCalendar currentCalendar];    
NSDate *tomorrow = [cal dateByAddingUnit:NSCalendarUnitDay 
                                   value:1 
                                  toDate:[NSDate date] 
                                 options: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];