iOS時間那點事--NSDate

weixin_33762321發表於2016-07-01

NSDate

NSTimeZone 網址:http://my.oschina.net/yongbin45/blog/151376
NSDateFormatter 網址: http://my.oschina.net/yongbin45/blog/150667

NSDate物件用來表示一個具體的時間點。
NSDate是一個類簇,我們所使用的NSDate物件,都是NSDate的私有子類的實體。
NSDate儲存的是GMT時間,使用的時候會根據 當前應用 指定的 時區 進行時間上的增減,以供計算或顯示。
可以快速地獲取的時間點有:

now (當前時間點)
相對於1 January 2001, GMT的時間點
相對於1970的時間點
distantFuture (不可達到的未來的某個時間點)
distantPast (不可達到的過去的某個時間點
根據http://www.gnustep.org/實現的NSDate的版本:


@interface NSDate : NSObject <NSCoding, NSCopying>
{
NSTimeInterval _secondsSinceRef;
}

……

  • (id) initWithTimeInterval:(NSTimeInterval) secsToBeAdded
    sinceDate:(NSDate *) anotherDate; 相對於已知的某個時間點
  • (id) initWithTimeIntervalSinceNow:(NSTimeInterval) secsToBeAdded; 相對於當前時間
  • (id) initWithTimeIntervalSince1970:(NSTimeInterval)seconds; 相對於1970年1月1日0時0分0秒
  • (id) initWithTimeIntervalSinceReferenceDate:(NSTimeInterval) secs; 相對於2001年1月1日0時0分0秒

……

@end
可以看出,NSDate類確實只是一個相對的時間點,NSTimeInterval的單位是秒(s),_secondsSinceRef則說明NSDate物件是相對於ReferenceDate(2001年1月1日0時0分0秒)的一個時間點。

同時,根據Cocoa框架的設計原則,每個類都有一個“指定初始化方法”(指定初始化方法是引數最全,且其他初始化方法都會呼叫的初始化方法)。http://www.gnustep.org/實現的版本以方法:

  • (id) initWithTimeIntervalSinceReferenceDate:(NSTimeInterval) secs;
    作為指定初始化方法,也就是說所有的時間點都轉化為了相對referenceDate的時間點(時間點都是相對的,因為時間本身就是相對的)。

NSDate中最常用的方法一般是:


NSDate *now = [NSDate date]; // [[NSDate alloc] init]
NSDate *dateFromNow = [NSDate dateWithTimeIntervalSinceNow:60];
NSDate *dateFromAnotherDate = [[NSDate alloc] initWithTimeInterval:60 sinceDate:dateFromNow];

NSTimeInterval timeInterval1 = [now timeIntervalSinceDate:dateFromNow];
NSTimeInterval timeInterval2 = [now timeIntervalSinceNow];

//-------------------------------------------------------------
NSDate *distantPast = [NSDate distantPast]; // 可以表示的最早的時間
NSDate *distantFuture = [NSDate distantFuture]; // 可以表示的最遠的未來時間

NSString *stringDate = @"12/31/9999";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"MM/dd/yyyy"];
NSDate *dateCheck = [dateFormatter dateFromString:stringDate];
NSLog(@"Date = %@", dateCheck);

Output:
Date = 1999-12-30 16:00:00 +0000

*iOS中用NSDate表示的時間只能在distantPast和distantFuture之間!
//-------------------------------------------------------------

相關文章