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

如果它是:

21st February 2011

它将变成:

22nd February 2011

或者如果它是:

31st December 2011

它将变成:

1st January 2012.

当前回答

斯威夫特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];

其他回答

使用下面的函数,并使用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?

使用以下代码:

NSDate *now = [NSDate date];
int daysToAdd = 1;
NSDate *newDate1 = [now dateByAddingTimeInterval:60*60*24*daysToAdd];

As

addTimeInterval

现在已弃用。

斯威夫特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”。

NSDate *now = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:now];
NSDate *startDate = [calendar dateFromComponents:components];
NSLog(@"StartDate = %@", startDate);

components.day += 1;
NSDate *endDate = [calendar dateFromComponents:components];
NSLog(@"EndDate = %@", endDate);