如何创建过去的新 NSDate 对象,例如比另一个日期早 1 秒?
How do I create a new NSDate object that is in the past, e.g. 1 second earlier than another date?
这就是我设置未来日期的方式:
var comp = NSDateComponents()
comp.setValue(1, forComponent: NSCalendarUnit.CalendarUnitMonth);
let date: NSDate = NSDate()
var expirationDate = NSCalendar.currentCalendar().dateByAddingComponents(comp, toDate: date, options: NSCalendarOptions(0))
现在,如果我有 dateA 并想创建一个比 dateA 早 1 秒的新日期 (dateB),该怎么办?
You can achieve this by changing your second line from 1 to -1
and NSCalendarUnit Month to Second
var comp = DateComponents()
comp.setValue(-1, for: .second)
let date = Date()
let expirationDate = NSCalendar.current.date(byAdding: comp, to: date)
希望对您有所帮助。
这就是我设置未来日期的方式:
var comp = NSDateComponents()
comp.setValue(1, forComponent: NSCalendarUnit.CalendarUnitMonth);
let date: NSDate = NSDate()
var expirationDate = NSCalendar.currentCalendar().dateByAddingComponents(comp, toDate: date, options: NSCalendarOptions(0))
现在,如果我有 dateA 并想创建一个比 dateA 早 1 秒的新日期 (dateB),该怎么办?
You can achieve this by changing your second line from
1 to -1
and NSCalendarUnitMonth to Second
var comp = DateComponents()
comp.setValue(-1, for: .second)
let date = Date()
let expirationDate = NSCalendar.current.date(byAdding: comp, to: date)
希望对您有所帮助。