iOS 獲取當前時間和當前時間戳

2022-04-04 14:48:28 字數 2165 閱讀 5249

//獲取當前的時間

+(nsstring*)getcurrenttimes{

nsdateformatter *formatter = [[nsdateformatter alloc] init];

// ----------設定你想要的格式,hh與hh的區別:分別表示12小時制,24小時制

[formatter setdateformat:@"yyyy-mm-dd hh:mm:ss"];

//現在時間,你可以輸出來看下是什麼格式

nsdate *datenow = [nsdate date];

//----------將nsdate按formatter格式轉成nsstring

nsstring *currenttimestring = [formatter stringfromdate:datenow];

nslog(@"currenttimestring =  %@",currenttimestring);

return currenttimestring;

獲取當前時間戳有兩種方法(以秒為單位)

+(nsstring *)getnowtimetimestamp{

nsdateformatter *formatter = [[nsdateformatter alloc] init] ;

[formatter setdatestyle:nsdateformattermediumstyle];

[formatter settimestyle:nsdateformattershortstyle];

[formatter setdateformat:@"yyyy-mm-dd hh:mm:ss"]; // ----------設定你想要的格式,hh與hh的區別:分別表示12小時制,24小時制

//設定時區,這個對於時間的處理有時很重要

nstimezone* timezone = [nstimezone timezonewithname:@"asia/shanghai"];

[formatter settimezone:timezone];

nsdate *datenow = [nsdate date];//現在時間,你可以輸出來看下是什麼格式

nsstring *timesp = [nsstring stringwithformat:@"%ld", (long)[datenow timeintervalsince1970]];

return timesp;

+(nsstring *)getnowtimetimestamp2{

nsdate* dat = [nsdate datewithtimeintervalsincenow:0];

nstimeinterval a=[dat timeintervalsince1970];

nsstring*timestring = [nsstring stringwithformat:@"%0.f", a];//轉為字元型

return timestring;

//獲取當前時間戳  (以毫秒為單位)

+(nsstring *)getnowtimetimesta***{

nsdateformatter *formatter = [[nsdateformatter alloc] init] ;

[formatter setdatestyle:nsdateformattermediumstyle];

[formatter settimestyle:nsdateformattershortstyle];

[formatter setdateformat:@"yyyy-mm-dd hh:mm:ss sss"]; // ----------設定你想要的格式,hh與hh的區別:分別表示12小時制,24小時制

//設定時區,這個對於時間的處理有時很重要

nstimezone* timezone = [nstimezone timezonewithname:@"asia/shanghai"];

[formatter settimezone:timezone];

nsdate *datenow = [nsdate date];//現在時間,你可以輸出來看下是什麼格式

nsstring *timesp = [nsstring stringwithformat:@"%ld", (long)[datenow timeintervalsince1970]*1000];

return timesp;

iOS 獲取當前時間和當前時間戳

獲取當前的時間 nsstring getcurrenttimes nsdateformatter formatter nsdateformatter alloc init 設定你想要的格式,hh與hh的區別 分別表示12小時制,24小時制 formatter setdateformat yyyy m...

iOS 獲取當前時間及時間戳的互換

在專案開發中,難免會遇到使用當前時間,比如實現網路請求上傳報文 預約 日曆等功能。1.獲取年月日時分秒 實現 nsdate date1 nsdate date nsdateformatter formatter1 nsdateformatter alloc init formatter1 setda...

iOS 獲取當前時間及時間戳的互換

在專案開發中,難免會遇到使用當前時間,比如實現網路請求上傳報文 預約 日曆等功能。1.獲取年月日時分秒 實現 nsdate date1 nsdate date nsdateformatter formatter1 nsdateformatter alloc init formatter1 setda...