從當前日期獲取 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);