如何解决如何获取正确格式的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。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。