C++ 格式化日期和时间戳
1. 格式化日期
参考: https://blog.csdn.net/K346K346/article/details/47735791
1.1 说明
localtime
函数获取日期信息,通过
strftime
函数格式化日期
localtime
是个线程不安全的函数,因为用到了全局变量。于是有了线程安全的
localtime_s
和
localtime_r
localtime_s
是适配windows平台的
localtime_r
是适配linux平台的
localtime_s
和
localtime_r
使用时,参数顺序不一样
1.2 基本用法
#include <time.h>
time_t t = time(0);
char tmp[32] = { NULL };
strftime(tmp, sizeof(tmp), "%Y-%m-%d_%H:%M:%S", localtime(&t));
string date(tmp);
date: (样例): 2015-04-02_23:12:56
1.3 windows localtime_s
struct tm stime;
time_t now = time(0);
localtime_s(&stime, &now);
char tmp[32] = { NULL };
strftime(tmp, sizeof(tmp), "%Y-%m-%d_%H:%M:%S", &stime);
string date(tmp);
1.4 linux localtime_r
struct tm stime;
time_t now = time(0);
localtime_r(&now, &stime);
char tmp[32] = { NULL };
strftime(tmp, sizeof(tmp), "%Y-%m-%d_%H:%M:%S", &stime);
string date(tmp);
1.5 通过平台编译宏统一使用
参考: https://stackoverflow.com/questions/38034033/c-localtime-this-function-or-variable-may-be-unsafe
inline std::tm localtime_xp(std::time_t timer)
std::tm bt {};
#if defined(__unix__)
localtime_r(&timer, &bt);
#elif defined(_MSC_VER)
localtime_s(&bt, &timer);
#else
static std::mutex mtx;
std::lock_guard<std::mutex> lock(mtx);
bt = *std::localtime(&timer);
#endif
return bt;
char tmp[32] = { NULL };
auto stime = localtime_xp(std::time(0));
strftime(tmp, sizeof(tmp), "%Y-%m-%d_%H:%M:%S", &stime);
string date(tmp);
2. 时间戳
2.1 秒级时间戳
#include<iostream>
#include<ctime>
int main()
std::time_t t = std::time(0); // t is an integer type
std::cout << t << " seconds since 01-Jan-1970\n";
return 0;
1554986565 seconds since 01-Jan-1970
#include <chrono>
auto now = std::chrono::system_clock::now();
auto in_time_t = std::chrono::system_clock::to_time_t(now);
2.2 毫秒级时间戳
#include <time.h>
#include <chrono>
auto now = std::chrono::system_clock::now();
std::chrono::time_point<std::chrono::system_clock,std::chrono::milliseconds> tp = std::chrono::time_point_cast<std::chrono::milliseconds>(now);//获取当前时间点
std::time_t timestamp = tp.time_since_epoch().count(); //计算距离1970-1-1,00:00的时间长度
c/c++ 标准日期和时间戳互相转化
https://blog.csdn.net/u011304615/article/details/71713179
3. 其他
目前获取日期的方法都不友好,在C++20之后估计会有改善
https://www.modernescpp.com/index.php/calendar-and-time-zone-in-c-20