Linux下用C獲取當前時間,具體如下:
代碼(可以把clock_gettime換成time(NULL))
void getNowTime(){ timespec time; clock_gettime(CLOCK_REALTIME, &time); //獲取相對于1970到現(xiàn)在的秒數(shù) tm nowTime; localtime_r(&time.tv_sec, &nowtime); char current[1024]; sprintf(current, "%04d%02d%02d%02d:%02d:%02d", nowTime.tm_year + 1900, nowTime.tm_mon, nowTime.tm_mday,   nowTime.tm_hour, nowTime.tm_min, nowTime.tm_sec);}分析:
clock_gettime()
函數(shù)"clock_gettime"是基于Linux C語言的時間函數(shù),他可以用于計算精度和納秒。
語法:
#include<time.h>int clock_gettime(clockid_t clk_id,struct timespec *tp);
參數(shù):
clk_id : 檢索和設置的clk_id指定的時鐘時間。
CLOCK_REALTIME:系統(tǒng)實時時間,隨系統(tǒng)實時時間改變而改變,即從UTC1970-1-1 0:0:0開始計時,中間時刻如果系統(tǒng)時間被用戶改成其他,則對應的時間相應改變
CLOCK_MONOTONIC:從系統(tǒng)啟動這一刻起開始計時,不受系統(tǒng)時間被用戶改變的影響 CLOCK_PROCESS_CPUTIME_ID:本進程到當前代碼系統(tǒng)CPU花費的時間 CLOCK_THREAD_CPUTIME_ID:本線程到當前代碼系統(tǒng)CPU花費的時間struct timespec{time_t tv_sec; /* 秒*/long tv_nsec; /* 納秒*/};localtime()
localtime是 把從1970-1-1零點零分到當前時間系統(tǒng)所偏移的秒數(shù)時間轉(zhuǎn)換為本地時間.
語法
說明:此函數(shù)獲得的tm結(jié)構體的時間是日歷時間。
用 法: struct tm *localtime(const time_t *clock);
返回值:返回指向tm 結(jié)構體的指針.tm結(jié)構體是time.h中定義的用于分別存儲時間的各個量(年月日等)的結(jié)構體.
例1:
#include <stdio.h>#include <stddef.h>#include <time.h>int main(void){ time_t timer;//time_t就是long int 類型 struct tm *tblock; timer = time(NULL); tblock = localtime(&timer); printf("Local time is: %s/n", asctime(tblock)); return 0;}執(zhí)行結(jié)果:
Local time is: Mon Feb 16 11:29:26 2009
例2:
上面的例子用了asctime函數(shù),下面這個例子不使用這個函數(shù)一樣能獲取系統(tǒng)當前時間。需要注意的是年份加上1900,月份加上1。
#include<time.h>#include<stdio.h>int main(){ struct tm *t; time_t tt; time(&tt); t = localtime(&tt); printf("%4d年%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); return 0;}localtime()與localtime_r()的區(qū)別
localtime():
#include <cstdlib> #include <iostream> #include <time.h> #include <stdio.h>  using namespace std;  int main(int argc, char *argv[]) {  time_t tNow =time(NULL);  time_t tEnd = tNow + 1800;  //注意下面兩行的區(qū)別  struct tm* ptm = localtime(&tNow);  struct tm* ptmEnd = localtime(&tEnd);   char szTmp[50] = {0};  strftime(szTmp,50,"%H:%M:%S",ptm);  char szEnd[50] = {0};  strftime(szEnd,50,"%H:%M:%S",ptmEnd);     printf("%s /n",szTmp);  printf("%s /n",szEnd);     system("PAUSE");  return EXIT_SUCCESS; }
新聞熱點
疑難解答
圖片精選