如何获取正确格式的UTC偏移量时区?

问题描述

我有这样的代码,可以将Epoch时间戳转换为GMT时间戳:

['usa','canada']

工作正常,除了我的时间戳是例如:

#include <array> #include <ctime> #include <string> std::string getDateTimeZ(size_t epoch) { const time_t time = epoch; const auto timeInfo = *localtime(&time); std::array<char,80> buffer; std::strftime(buffer.data(),buffer.size(),"%Y-%m-%dT%H:%M:%S%z",&timeInfo); return buffer.data(); }

我希望它是

2020-09-10T20:53:10+0300

如何在不对结果字符串进行丑陋且易于出错的破解的情况下立即执行此操作?除了2020-09-10T20:53:10+03:00之外,我没有看到其他任何获得偏移量的选项。

Boost之类的其他库也可以接受。

解决方法

您可以使用此preview of the C++20 <chrono> facilities,它与C + 11一起使用:

#include "date/tz.h"
#include <chrono>
#include <cstddef>
#include <string>
#include <sstream>

std::string
getDateTimeZ(std::size_t epoch)
{
    using namespace date;
    using namespace std::chrono;
    zoned_seconds zt{current_zone(),sys_seconds{seconds{epoch}}};
    std::ostringstream os;
    os << format("%FT%T%Ez",zt);
    return os.str();
}

该库的窍门是使用%Ez代替%z

此库确实需要some installation

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...