从当前日期获取 NSDate 对象 N 秒
新日期的当前日期和时间的秒数。使用负值指定当前日期之前的日期。
为此,我们有一个名为 dateWithTimerIntervalSinceNow(seconds: NSTimeInterval) -> NSDate
(Swift)或+ (NSDate*)dateWithTimeIntervalSinceNow:(NSTimeInterval)seconds
(Objective-C)的方法。
现在,例如,如果你需要从当前日期和一周到当前日期一周的日期,那么我们可以这样做。
迅速
let totalSecondsInWeek:NSTimeInterval = 7 * 24 * 60 * 60;
//Using negative value for previous date from today
let nextWeek = NSDate().dateWithTimerIntervalSinceNow(totalSecondsInWeek)
//Using positive value for future date from today
let lastWeek = NSDate().dateWithTimerIntervalSinceNow(-totalSecondsInWeek)
Swift 3
let totalSecondsInWeek:TimeInterval = 7 * 24 * 60 * 60;
//Using positive value to add to the current date
let nextWeek = Date(timeIntervalSinceNow: totalSecondsInWeek)
//Using negative value to get date one week from current date
let lastWeek = Date(timeIntervalSinceNow: -totalSecondsInWeek)
Objective-C
NSTimeInterval totalSecondsInWeek = 7 * 24 * 60 * 60;
//Using negative value for previous date from today
NSDate *lastWeek = [NSDate dateWithTimeIntervalSinceNow:-totalSecondsInWeek];
//Using positive value for future date from today
NSDate *nextWeek = [NSDate dateWithTimeIntervalSinceNow:totalSecondsInWeek];
NSLog(@"Last Week: %@", lastWeek);
NSLog(@"Right Now: %@", now);
NSLog(@"Next Week: %@", nextWeek);