问题描述
我有这样的代码,可以将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。