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小时

GitHub:https://github.com/fengbingchun/Messy_Test

你可能感兴趣的:(C/C++/C++11)