适用于iOS swift的Calendar API

时间:2015-01-05 20:26:04

标签: swift calendar

我正在寻找一个从今天到今天返回日期的API,我很确定有很多,但我找不到适合iOS swift的日期。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

extension NSDate {
    func xYears(x:Int)       -> NSDate { return NSCalendar.currentCalendar().dateByAddingUnit(.CalendarUnitYear,        value: x, toDate: self, options: nil)! }
    func xQuarters(x:Int)    -> NSDate { return NSCalendar.currentCalendar().dateByAddingUnit(.CalendarUnitQuarter,     value: x, toDate: self, options: nil)! }
    func xMonths(x:Int)      -> NSDate { return NSCalendar.currentCalendar().dateByAddingUnit(.CalendarUnitMonth,       value: x, toDate: self, options: nil)! }
    func xWeeks(x:Int)       -> NSDate { return NSCalendar.currentCalendar().dateByAddingUnit(.CalendarUnitWeekOfYear,  value: x, toDate: self, options: nil)! }
    func xDays(x:Int)        -> NSDate { return NSCalendar.currentCalendar().dateByAddingUnit(.CalendarUnitDay,         value: x, toDate: self, options: nil)! }
    func xHours(x:Int)       -> NSDate { return NSCalendar.currentCalendar().dateByAddingUnit(.CalendarUnitHour,        value: x, toDate: self, options: nil)! }
    func xMinutes(x:Int)     -> NSDate { return NSCalendar.currentCalendar().dateByAddingUnit(.CalendarUnitMinute,      value: x, toDate: self, options: nil)! }
    func xSeconds(x:Int)     -> NSDate { return NSCalendar.currentCalendar().dateByAddingUnit(.CalendarUnitSecond,      value: x, toDate: self, options: nil)! }
    func xNanoseconds(x:Int) -> NSDate { return NSCalendar.currentCalendar().dateByAddingUnit(.CalendarUnitNanosecond,  value: x, toDate: self, options: nil)! }
}

NSDate().xYears(2)  // "Jan 5, 2017, 8:03 PM"
NSDate().xMonths(2) // "Mar 5, 2015, 8:03 PM"
NSDate().xDays(2)   // "Jan 7, 2015, 8:03 PM"