我正在寻找一个从今天到今天返回日期的API,我很确定有很多,但我找不到适合iOS swift的日期。有什么建议吗?
答案 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"