C++時間戳轉(zhuǎn)化操作實例分析【涉及GMT與CST時區(qū)轉(zhuǎn)化】
本文實例講述了C++時間戳轉(zhuǎn)化操作。分享給大家供大家參考,具體如下:
問題由來
時間戳轉(zhuǎn)換(時間戳:自 1970 年1月1日(00:00:00 )至當前時間的總秒數(shù)。)
#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);
}
結(jié)果
1408413451 2014-08-19 01:57:1408384651
可是利用命令在linux終端計算的結(jié)果不一
[###t]$ date -d @1408413451 Tue Aug 19 09:57:31 CST 2014
通過比較發(fā)現(xiàn),兩者正好差8個小時,CST表示格林尼治時間,通過strftime()函數(shù)可以輸出時區(qū),改正如下
#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);
}
結(jié)果
1408413451: 2014-08-19 01:57:31::GMT
深究
GMT(Greenwich Mean Time)代表格林尼治標準時間。十七世紀,格林威治皇家天文臺為了海上霸權(quán)的擴張計畫而進行天體觀測。1675年舊皇家觀測所正式成立,通過格林威治的子午線作為劃分地球東西兩半球的經(jīng)度零度。觀測所門口墻上有一個標志24小時的時鐘,顯示當下的時間,對全球而言,這里所設定的時間是世界時間參考點,全球都以格林威治的時間作為標準來設定時間,這就是我們耳熟能詳?shù)摹父窳滞螛藴蕰r間」(Greenwich Mean Time,簡稱G.M.T.)的由來。
CST卻同時可以代表如下 4 個不同的時區(qū):
Central Standard Time (USA) UT-6:00 Central Standard Time (Australia) UT+9:30 China Standard Time UT+8:00 Cuba 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;
}
結(jié)果
1408413451: 2014-08-19 01:57:31::GMT 1408442251: 2014-08-19 09:57:31
linux平臺
Tue Aug 19 09:57:31 CST 2014
PS:本站還提供了一個Unix時間戳轉(zhuǎn)換工具,包含了各種常見語言針對時間戳的操作方法,提供給大家參考:
Unix時間戳(timestamp)轉(zhuǎn)換工具:
http://tools.jb51.net/code/unixtime
希望本文所述對大家C++程序設計有所幫助。
相關(guān)文章
詳解C++中十六進制字符串轉(zhuǎn)數(shù)字(數(shù)值)
這篇文章主要介紹了詳解C++中十六進制字符串轉(zhuǎn)數(shù)字(數(shù)值)的相關(guān)資料,這里提供兩種實現(xiàn)方法,需要的朋友可以參考下2017-08-08

