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

如果它是:

21st February 2011

它将变成:

22nd February 2011

或者如果它是:

31st December 2011

它将变成:

1st January 2012.

当前回答

在Swift 2.1.1和xcode 7.1 OSX 10.10.5中,你可以使用函数添加任意数量的天数

func addDaystoGivenDate(baseDate:NSDate,NumberOfDaysToAdd:Int)->NSDate
{
    let dateComponents = NSDateComponents()
    let CurrentCalendar = NSCalendar.currentCalendar()
    let CalendarOption = NSCalendarOptions()

    dateComponents.day = NumberOfDaysToAdd

    let newDate = CurrentCalendar.dateByAddingComponents(dateComponents, toDate: baseDate, options: CalendarOption)
    return newDate!
}

函数调用,将当前日期增加9天

var newDate = addDaystoGivenDate(NSDate(), NumberOfDaysToAdd: 9)
print(newDate)

函数调用,将当前日期减少80天

newDate = addDaystoGivenDate(NSDate(), NumberOfDaysToAdd: -80)
 print(newDate)

其他回答

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

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

对于swift 2.2:

let today = NSDate()
let tomorrow = NSCalendar.currentCalendar().dateByAddingUnit(
        .Day,
        value: 1,
        toDate: today,
        options: NSCalendarOptions.MatchStrictly)

希望这能帮助到一些人!