C++中獲取日期函數gmtime和localtime區別

函數gmtime和localtime的聲明如下:

struct tm * gmtime (const time_t * timer);
struct tm * localtime (const time_t * timer);

它們均接收一個time_t的const指針類型,time_t類型通常是一個大整數值,該整數值表示自UTC時間1970年1月1日00:00以來經過的秒數即UNIX時間戳,可直接調用time函數獲取,如下面測試代碼中的time(&rawtime)語句。

它們均返回類型爲tm的結構體指針。此結構體的聲明如下:由此可見gmtime和localtime函數主要做的就是將大整數值rawtime轉換成易讀取的時間,如可快速獲取年、月、日等。

struct tm {
	int tm_sec;   // seconds after the minute - [0, 60] including leap second
	int tm_min;   // minutes after the hour - [0, 59]
	int tm_hour;  // hours since midnight - [0, 23]
	int tm_mday;  // day of the month - [1, 31]
	int tm_mon;   // months since January - [0, 11]
	int tm_year;  // years since 1900
	int tm_wday;  // days since Sunday - [0, 6]
	int tm_yday;  // days since January 1 - [0, 365]
	int tm_isdst; // daylight savings time flag
};

gmtime和localtime區別:

(1).gmtime將time_t轉換爲UTC時間,UTC的全稱爲Coordinated Universal Time,即世界標準時間。

(2).localtime將time_t轉換爲本地時間(local time)。北京時間比UTC時間早8小時。

測試代碼段如下:

void print_time(const std::string& type, const struct tm* timeinfo)
{
	int year = timeinfo->tm_year + 1900; // years since 1900
	int month = timeinfo->tm_mon + 1; // months since January - [0, 11]
	int day = timeinfo->tm_mday;
	int date = year * 10000 + month * 100 + day;

	int hour = timeinfo->tm_hour;
	int minute = timeinfo->tm_min;
	int second = timeinfo->tm_sec;

	fprintf(stdout, "type: %s\t, date: %d, time: %.2d:%.2d:%.2d\n", type.c_str(), date, hour, minute, second);
}

int test_gmtime_localtime()
{
{ // gmtime
	time_t rawtime;
	time(&rawtime);

	struct tm* timeinfo = gmtime(&rawtime);
	print_time("UTC", timeinfo);
}

{ // localtime
	time_t rawtime;
	time(&rawtime);

	struct tm* timeinfo = localtime(&rawtime);
	print_time("localtime", timeinfo);
}

	return 0;
}

執行結果如下:localtime比UTC早8小時

GitHubhttps://github.com/fengbingchun/Messy_Test

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章