1.time_t转为字符串输出
api:
localtime_s --将time_t转为tm结构体
strftime --将tm格式化输出
代码如下:
#include <iostream>
//#include <chrono>
#include <ctime>
int main()
{
/*std::chrono::system_clock::time_point tp = std::chrono::system_clock::now();
__time64_t time_now = std::chrono::system_clock::to_time_t(tp);*/
/*char _time[250];
ctime_s(_time, sizeof(_time), &time_now);
cout << "now time is : " << _time;*/
//计算距离1970-1-1,00:00的时间长度,因为当前时间点定
/*char buf[250];
tm local_time;
localtime_s(&local_time, &time_now);
strftime(buf, sizeof(buf), "%Y-%m-%d,%H:%M:%S", &local_time);
cout << "now time is : " << buf;*/
time_t rawtime;
struct tm info;
char buffer[80];
time(&rawtime);
localtime_s(&info, &rawtime); //将time_t转为tm
strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", &info);
printf("格式化的日期 & 时间 : |%s|\n", buffer);
system("pause");
return 0;
}
注意:
1.localtime、localtime_s、localtime_r
功能:将time_t转为tm结构体
localtime是非线程安全的,localtime_s、localtime_r都是线程安全的,但是localtime_s是windows平台的,localtime_r是linux平台的
2.ctime、ctime_s、strftime
功能:将tm转为字符串显示
ctime返回一个指向静态数据的指针并且不是线程安全的,C标准也建议strftime不要使用ctime、ctime_s,因为strftime它更灵活且对语言环境敏感
3.tm结构体与时间显示
struct tm的结构为
int tm_sec; /* 秒 – 取值区间为[0,59] */
int tm_min; /* 分 - 取值区间为[0,59] */
int tm_hour; /* 时 - 取值区间为[0,23] */
int tm_mday; /* 一个月中的日期 - 取值区间为[1,31] */
int tm_mon; /* 月份(从一月开始,0代表一月) - 取值区间为[0,11] */
int tm_year; /* 年份,其值等于实际年份减去1900 */
int tm_wday; /* 星期 – 取值区间为[0,6],其中0代表星期天,1代表星期一,以此类推 */
int tm_yday; /* 从每年的1月1日开始的天数 – 取值区间为[0,365],其中0代表1月1日,1代表1月2日,以此类推 */
int tm_isdst; /* 夏令时标识符,实行夏令时的时候,tm_isdst为正。不实行夏令时的进候,tm_isdst为0;不了解情况时,tm_isdst()为负。*/
时间显示:
#include <iostream>
#include <time.h>
int main()
{
time_t time_seconds = time(0);
struct tm now_time;
localtime_s(&now_time, &time_seconds);
printf("%d-%d-%d %d:%d:%d/n", now_time.tm_year + 1900, now_time.tm_mon + 1, now_time.tm_mday, now_time.tm_hour, now_time.tm_min, now_time.tm_sec);
}
注意:
(1)tm_year并不是实际年份,tm_year值等于实际年份减去1900
应用:
已知tm_year,那么实际显示时的年份为(tm_year+1900)
已知实际显示年份,转为tm结构体时,里面年份为(实际年份-1900)
(2)tm_mon月份(从一月开始,0代表一月) - 取值区间为[0,11]
实际显示是要加1进行显示
4.time_t与tm结构体相互转换
api:
localtime_s --将time_t转为tm结构体
mktime --将tm转为time_t结构体
time_t rawtime;
struct tm info;
char buffer[80];
time(&rawtime);
localtime_s(&info, &rawtime);//将time_t转为tm
time_t dd = std::mktime(&info);//将tm转为time_t