獲取本地時間

2021-08-04 16:54:33 字數 1369 閱讀 5172

// 獲取本地時間戳

int gettimestamp()

timeval tm;

gettimeofday(&tm, null);

return tm.tv_sec;    // 單位:秒

//    return tm.tv_usec; // 單位:毫秒

{ //獲取本地時間

time_t t = time(null);

tm* lt = localtime(&t);

int year = lt->tm_year + 1900;  // 相對

1900

年的過去的年數

int month = lt->tm_mon + 1;     // 1月份:為0

int yday = lt->tm_yday;         // 年第幾天:從1開始

int mday = lt->tm_mday;         // 月第幾天:從1開始

int wday = lt->tm_wday;         // 周第幾天:從1開始

int hh = lt->tm_hour;           // 時

int mm = lt->tm_min;            // 分

int ss = lt->tm_sec;            // 秒

printf("%d %d\n", year, month);

printf("%d %d %d\n", yday, mday, wday);

printf("%d %d %d\n", hh, mm, ss);

第一種:優點:僅使用c標準庫;缺點:只能精確到秒級

time_t tt = time(null);//這句返回的只是乙個時間戳

tm* t= localtime(&tt);

printf("%d-%02d-%02d %02d:%02d:%02d\n", t->tm_year + 1900, t->tm_mon + 1,

t->tm_mday,t->tm_hour,t->tm_min,t->tm_sec);

第二種:優點:能精確到毫秒級;缺點:使用了windows api

#include

#include

int main( void )

systemtime sys;

getlocaltime( &sys );

printf("%4d/%02d/%02d%02d:%02d:%02d.%03d 星期

%1d\n",sys.wyear,sys.wmonth,sys.wday,sys.whour,sys.wminute, sys.wsecond,sys.wmilliseconds,sys.wdayofweek);

return 0;

獲取本地時間

獲取本地時間 struct tm tm time t timep if cc target platform cc platform win32 else localtime 功能 把從1970 1 1零點零分到當前時間系統所偏移的秒數時間轉換為日曆時間。說明 此函式獲得的tm結構體的時間,是已經進...

Linux獲取本地時間

參考鏈結 linux核心中表示時間的結構體和資料型別有5種,具體其宣告的標頭檔案在 include include extern void do gettimeofday struct timeval tv gettimeofday函式執行成功後返回0,失敗後返回 1,錯誤 存於errno中。ext...

objectiveC獲取本地時間。

nsdate date nscalendardate date nslog date 日曆在ios裡報錯,nsdateformatter formatter nsdateformatteralloc init formatter setdateformat yyyy mm dd hh mm ss n...