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

如果它是:

21st February 2011

它将变成:

22nd February 2011

或者如果它是:

31st December 2011

它将变成:

1st January 2012.

当前回答

NSDate *today=[NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents *components=[[NSDateComponents alloc] init];
components.day=1;
NSDate *targetDate =[calendar dateByAddingComponents:components toDate:today options: 0];

其他回答

它的工作原理!

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

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

你可以使用NSDate的方法- (id)dateByAddingTimeInterval:(NSTimeInterval)秒,其中秒为60 * 60 * 24 = 86400

只是为了好玩,通过一些扩展和操作符重载,你可以得到一些不错的东西,比如:

let today = Date()
let tomorrow = today + 1.days

, or

var date = Date()
date += 1.months

下面是支持代码:

extension Calendar {
    struct ComponentWithValue {
        let component: Component
        let value: Int
    }
}

extension Int {
    var days: Calendar.ComponentWithValue {
        .init(component: .day, value: self)
    }
    
    var months: Calendar.ComponentWithValue {
        .init(component: .month, value: self)
    }
}

func +(_ date: Date, _ amount: Calendar.ComponentWithValue) -> Date {
    Calendar.current.date(byAdding: amount.component, value: amount.value, to: date)!
}

func +(_ amount: Calendar.ComponentWithValue, _ date: Date) -> Date {
    date + amount
}

func +=(_ date: inout Date, _ amount: Calendar.ComponentWithValue) {
    date = date + amount
}

代码是最少的,并且可以很容易地扩展到允许.月,.年,.小时等。还可以无缝添加对减法(-)的支持。

虽然在+操作符的实现中有一个强制的展开,但是不确定在哪种情况下日历可以返回nil日期。