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
时间转年月日时分秒
c++20时间转年月日代码如下:
转年月日:
std::chrono::year_month_day ymd{ std::chrono::floor< std::chrono::days>(zt.get_local_time()) };
转时分秒:
std::chrono::hh_mm_ss hms { zt.get_local_time() - std::chrono::floor<std::chrono::days>(zt.get_local_time()) };
完整代码如下:
#include <iostream>
#include <chrono>
int main()
{
//获取当前时间
std::chrono::time_point fNow = std::chrono::system_clock::now();
std::chrono::zoned_time zt{ std::chrono::current_zone() ,std::chrono::clock_cast<std::chrono::system_clock>(fNow) };
//输出年月日
std::chrono::year_month_day ymd{ std::chrono::floor< std::chrono::days>(zt.get_local_time()) };
std::cout << ymd.year().operator int() << "-" << ymd.month().operator unsigned int() << "-" << ymd.day().operator unsigned int() << std::endl;
//输出时分秒
std::chrono::hh_mm_ss hms { zt.get_local_time() - std::chrono::floor<std::chrono::days>(zt.get_local_time()) };
std::cout << hms.hours().count() << ":" << hms.minutes().count() << ":" << hms.seconds().count() << std::endl;
getchar();
}
输出结果:
2024-10-31
9:30:52