#include <chrono>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
inline std::string ToString(const std::chrono::system_clock::time_point &tp)
{
std::time_t time = std::chrono::system_clock::to_time_t(tp);
// std::string ts = std::ctime(&t);
// ts.resize(ts.size() - 1);
// return ts;
// std::tm *tm = std::gmtime(&time);
std::tm *tm = std::localtime(&time);
std::stringstream sstream;
sstream << std::put_time(tm, "%F %T");
return sstream.str();
}
inline std::chrono::system_clock::time_point MakeTimePoint(
int year, int month, int day,
int hour = 0, int minute = 0, int second = 0)
{
struct std::tm t;
t.tm_year = year - 1900;
t.tm_mon = month - 1;
t.tm_mday = day;
t.tm_hour = hour;
t.tm_min = minute;
t.tm_sec = second;
t.tm_isdst = -1;
std::time_t tt = std::mktime(&t);
if (tt == -1)
{
std::stringstream sstream;
sstream << "Invalid system time(std::tm.tm_isdst = ";
sstream << t.tm_isdst;
sstream << ")";
throw sstream.str();
}
return std::chrono::system_clock::from_time_t(tt);
}
int main()
{
try
{
auto tp1 = MakeTimePoint(2010, 1, 1);
std::cout << ToString(tp1) << std::endl;
auto tp2 = MakeTimePoint(2011, 5, 23, 13, 44);
std::cout << ToString(tp2) << std::endl;
auto now = std::chrono::system_clock::now();
std::cout << ToString(now) << std::endl;
}
catch (std::string str)
{
std::cerr << str << std::endl;
}
}
[编程语言][C++]时间处理
最新推荐文章于 2025-02-22 19:52:22 发布
该代码示例展示了如何在C++中使用chrono库将时间点转换为字符串,并创建自定义时间点。主要函数包括`ToString`用于将`system_clock::time_point`对象转化为日期时间格式的字符串,以及`MakeTimePoint`用于创建`time_point`对象。程序还演示了处理当前时间并打印结果。
442

被折叠的 条评论
为什么被折叠?



