本文實例講述了C++時間戳轉化操作。分享給大家供大家參考,具體如下:
問題由來
時間戳轉換(時間戳:自 1970 年1月1日(00:00:00 )至當前時間的總秒數。)
#include <stdio.h>#include <time.h>int main(int argc, const char * argv[]){ time_t t; struct tm *p; t=1408413451; p=gmtime(&t); char s[80]; strftime(s, 80, "%Y-%m-%d %H:%M:%S", p); printf("%d: %s/n", (int)t, s);}結果
1408413451 2014-08-19 01:57:1408384651
可是利用命令在linux終端計算的結果不一
[###t]$ date -d @1408413451Tue Aug 19 09:57:31 CST 2014
通過比較發現,兩者正好差8個小時,CST表示格林尼治時間,通過strftime()函數可以輸出時區,改正如下
#include <stdio.h>#include <time.h>int main(int argc, const char * argv[]){ time_t t; struct tm *p; t=1408413451; p=gmtime(&t); char s[80]; strftime(s, 80, "%Y-%m-%d %H:%M:%S::%Z", p); printf("%d: %s/n", (int)t, s);}結果
1408413451: 2014-08-19 01:57:31::GMT
深究
GMT(Greenwich Mean Time)代表格林尼治標準時間。十七世紀,格林威治皇家天文臺為了海上霸權的擴張計畫而進行天體觀測。1675年舊皇家觀測所正式成立,通過格林威治的子午線作為劃分地球東西兩半球的經度零度。觀測所門口墻上有一個標志24小時的時鐘,顯示當下的時間,對全球而言,這里所設定的時間是世界時間參考點,全球都以格林威治的時間作為標準來設定時間,這就是我們耳熟能詳的「格林威治標準時間」(Greenwich Mean Time,簡稱G.M.T.)的由來。
CST卻同時可以代表如下 4 個不同的時區:
Central Standard Time (USA) UT-6:00Central Standard Time (Australia) UT+9:30China Standard Time UT+8:00Cuba Standard Time UT-4:00
可見,CST可以同時表示美國,澳大利亞,中國,古巴四個國家的標準時間。
好了兩者差8個小時(CST比GMT晚/大8個小時),GMT+8*3600=CST,代碼如下
#include <stdio.h>#include <time.h>int main(int argc, const char * argv[]){ time_t t; struct tm *p; t=1408413451; p=gmtime(&t); char s[80]; strftime(s, 80, "%Y-%m-%d %H:%M:%S::%Z", p); printf("%d: %s/n", (int)t, s); t=1408413451 + 28800; p=gmtime(&t); strftime(s, 80, "%Y-%m-%d %H:%M:%S", p); printf("%d: %s/n", (int)t, s); return 0;}結果
1408413451: 2014-08-19 01:57:31::GMT1408442251: 2014-08-19 09:57:31
linux平臺
Tue Aug 19 09:57:31 CST 2014
PS:本站還提供了一個Unix時間戳轉換工具,包含了各種常見語言針對時間戳的操作方法,提供給大家參考:
Unix時間戳(timestamp)轉換工具:
http://tools.VeVB.COm/code/unixtime
希望本文所述對大家C++程序設計有所幫助。
新聞熱點
疑難解答
圖片精選