C++日期时间库

tm 返回具体格式

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
};

1、获取本地日期时间 格式:1999年09月09日 12时12分12秒

localtime()已被localtime_s()取而代之,localtime()在多线程开发中是不安全的

#include <iostream>
#include <ctime>
using namespace std;
int main()
{
	//日期和时间
	time_t time_seconds = time(0);
	struct tm now_time;
	localtime_s(&now_time, &time_seconds);
	printf("%d年%02d月%02d日 %02d时%02d分%02d秒\n",	
        now_time.tm_year + 1900,//当前年份数值是从1900~当前,这里要加上年份基数1900									
        now_time.tm_mon+1,//月份取值[0~11]这里需要手动+1								
        now_time.tm_mday, 									
        now_time.tm_hour, 									
        now_time.tm_min, 									
        now_time.tm_sec);
}

运行结果

在Linux中使用localtime_r()函数

2、日期转为数字

win32  t返回long型    win64  t返回__int64

void Call_TimeToInt()
	{
		tm info;
		info.tm_year = 2019-1900;
		info.tm_mon = 9 - 1;
		info.tm_mday = 9;
		info.tm_hour = 12;
		info.tm_min = 12;
		info.tm_sec = 30;
		time_t t = mktime(&info);
		printf("时间int=%d", t);
	}

猜你喜欢

转载自blog.csdn.net/glblove1986/article/details/89015621