C++20 时间转本地时间,时间转字符串以及字符串转时间的方法
时间转本地时间
下面的例子,获取文件最后修改时间,并转换为本地时间:
std::filesystem::path p{u8"D:/1.csv"};std::chrono::file_time pFile = std::filesystem::last_write_time(p);std::chrono::zoned_time zt { std::chrono::current_zone() ,std::chrono::clock_cast<std::chrono::system_clock>(pFile) };
时间转字符串:
std::chrono::zoned_time zt { std::chrono::current_zone() ,std::chrono::clock_cast<std::chrono::system_clock>(pFile) };{std::string str = std::format("{0:%Y}-{0:%m}-{0:%d} {0:%OH}:{0:%M}:{0:%S}", zt.get_sys_time());std::cout << str << std::endl;}
字符串转时间
std::chrono::sys_time<std::chrono::milliseconds> t;{std::stringstream s;s << str;std::chrono::from_stream(s, "%F %T", t);std::cout << t << std::endl;}
完整代码如下:
#include <filesystem>
#include <iostream>
#include <format>int main()
{ std::filesystem::path p{u8"D:/1.csv"};//从文件获取最后写入时间std::chrono::file_time pFile = std::filesystem::last_write_time(p);//转本地时间std::chrono::zoned_time zt { std::chrono::current_zone() ,std::chrono::clock_cast<std::chrono::system_clock>(pFile) };{//时间(utc)转字符串std::string str = std::format("{0:%Y}-{0:%m}-{0:%d} {0:%OH}:{0:%M}:{0:%S}", zt.get_sys_time());std::cout << str << std::endl;}{//时间(本地)转字符串std::string str = std::format("{0:%F} {0:%T}", zt.get_local_time());std::cout << str << std::endl;{//字符串转时间std::chrono::sys_time<std::chrono::milliseconds> t;std::stringstream s;s << str;std::chrono::from_stream(s, "%F %T", t);std::cout << t << std::endl;}} getchar();return 0;
}
运行结果如下:
2024-07-01 05:24:02.0000000
2024-07-01 13:24:02.0000000
2024-07-01 13:24:02.000