NSDate總結 學習筆記

2021-07-09 03:22:34 字數 1693 閱讀 1299

nsdate是用作處理日期的類。

1、建立初始化nsdate類的方法:

(1)當前日期

nsdate*date=[nsdatedate];

(2)根據當前時間建立,正數是當前時間過多少秒後的時間,負數是當前時間前多少秒的時間

nsdate*date1=[nsdatedatewithtimeintervalsincenow:60];

(3)根據某乙個nsdate來建立時間

nsdate*date1=[nsdatedatewithtimeinterval:63 sincedate:date];

(4)根據2023年1月1日0時0分0秒來建立時間

nsdate*date1=[nsdatedatewithtimeintervalsince1970:12345];

(5)根據2023年01月01 日0時0分0秒來建立時間

nsdate

*date1=[nsdate datewithtimeintervalsincereferencedate:sec];

2.時間的比較

- (bool)isequaltodate:(nsdate *)otherdate;

與otherdate比較,相同返回

yes

- (nsdate *)earlierdate:(nsdate *)anotherdate;

與anotherdate比較,返回較早的那個日期

- (nsdate *)laterdate:(nsdate *)anotherdate;

與anotherdate比較,返回較晚的那個日期

- (nscomparisonresult)compare:(nsdate *)other;

該方法用於排序時呼叫:

. 當例項儲存的日期值與anotherdate相同時返回nsorderedsame

. 當例項儲存的日期值晚於anotherdate時返回nsordereddescending

. 當例項儲存的日期值早於anotherdate時返回nsorderedascending

3.nsdate與nsstring的轉換

nsdate與nsstring的轉換通過nsdateformatter來實現,先建立nsdateformatter

nsdateformatter*format=[[nsdateformatteralloc]init];

在設定轉換格式:

[format

setdateformat

:@"yyyy-mm-dd hh:mm:ss"];

格式具體如圖:

日期轉換為nsstring:

nsstring *datestr=[format stringfromdate:date];

輸出的字元處為:

nsstring轉換為日期:

nsdate *date1=[format datefromstring:datestr];

輸出的nsdate為:

4.時間戳

時間戳(timestamp),通常是乙個字串行,唯一地標識某一刻的時間。數字時間戳技術是數字簽名技術一種變種的應⽤。根據1970獲得時間戳

nstimeintervaltime1=[date timeintervalsince1970];

輸出結果:

NSDate 使用總結

1 當前時間建立nsdate nsdate mydate nsdate date nslog mydate mydate 2 從現在開始的24小時 nstimeinterval secondsperday 24 60 60 nsdate tomorrow nsdate datewithtimeint...

NSDate 總結日期操作

nsdate 1,建立nsdate物件 nsdate nowdate nsdate date nslog nowdate 2,建立明天現在的時間 nsdate tomorrow nsdate datewithtimeintervalsincenow 24 3600 nslog tomorrow 3,...

iOS學習筆記 (5)NSDate和NSTimer

nsdate類的使用 1 建立日期物件 nsdate date1 nsdate alloc init nslog date1 預設格林尼治時間相差 8個時區 2 nsdate date2 nsdate date 返回乙個從1970 01 01 00 00 00 後一段時間的時間 date2 nsda...