如何通过时区与时间参数编程创建std::chrono::zoned_time?
实现从指定时区和时间创建std::chrono::zoned_time
一、基于年月日时分秒的函数实现
直接通过给定时间分量构造本地时间点,结合指定时区生成zoned_time:
#include <chrono> #include <string> std::chrono::zoned_time<std::chrono::seconds> get_zt(const std::string& location, int year, int month, int day, int hour, int minutes, int seconds) { const auto* tz = std::chrono::locate_zone(location); using namespace std::chrono; local_seconds local_t = year(year)/month(month)/day(day) + hours(hour) + minutes(minutes) + seconds(seconds); return {tz, local_t}; }
二、基于时间字符串的函数实现(不依赖parse/from_stream)
手动解析YYYY-MM-DD HH:MM:SS格式的时间字符串,提取时间分量后复用上述逻辑:
#include <chrono> #include <string> #include <sstream> #include <vector> std::vector<int> split_time_str(const std::string& time_str) { std::vector<int> parts; std::stringstream ss(time_str); std::string token; // 处理-、空格、:三种分隔符 while (std::getline(ss, token, '-') || std::getline(ss, token, ' ') || std::getline(ss, token, ':')) { if (!token.empty()) { parts.push_back(std::stoi(token)); } } return parts; } std::chrono::zoned_time<std::chrono::seconds> get_zt(const std::string& location, const std::string& time_str) { auto parts = split_time_str(time_str); if (parts.size() != 6) { throw std::invalid_argument("时间字符串格式错误,需为YYYY-MM-DD HH:MM:SS"); } return get_zt(location, parts[0], parts[1], parts[2], parts[3], parts[4], parts[5]); }
三、计算距离纪元的秒数
通过zoned_time的get_sys_time()方法获取对应UTC时间点,再转换为纪元以来的秒数:
#include <iostream> int main() { // 示例:纽约时间2024-05-20 10:30:00 auto zt = get_zt("America/New_York", 2024, 5, 20, 10, 30, 0); auto sys_t = zt.get_sys_time(); auto seconds_since_epoch = std::chrono::duration_cast<std::chrono::seconds>(sys_t.time_since_epoch()).count(); std::cout << "距离纪元的秒数:" << seconds_since_epoch << std::endl; // 时间字符串示例:伦敦时间2024-05-20 15:30:00 auto zt_str = get_zt("Europe/London", "2024-05-20 15:30:00"); auto sys_t_str = zt_str.get_sys_time(); auto seconds_since_epoch_str = std::chrono::duration_cast<std::chrono::seconds>(sys_t_str.time_since_epoch()).count(); std::cout << "距离纪元的秒数(字符串输入):" << seconds_since_epoch_str << std::endl; return 0; }
注意:
- 编译时需启用C20标准(g添加参数
-std=c++20),并确保系统包含tzdata时区数据 - 时区标识符需使用IANA标准名称(如
Asia/Shanghai、Europe/Paris)
内容的提问来源于stack exchange,提问作者Miro Kropacek
相关产品推荐
相关产品推荐

