【问题标题】:How to get UTC offset (timezone) in correct format?如何以正确的格式获取 UTC 偏移量(时区)?
【发布时间】:2020-12-29 06:42:07
【问题描述】:

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

#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

如何开箱即用地执行此操作,而不会对结果字符串进行丑陋且容易出错的 hack?除了%z,我看不到任何其他获得偏移量的选项。

其他一些库,如 Boost 也是可以接受的。

【问题讨论】:

    标签: c++ datetime c++11 strftime gmt


    【解决方案1】:

    您可以使用此preview of the C++20 &lt;chrono&gt; 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-06
      • 2010-11-19
      • 2016-05-07
      • 2013-10-15
      • 2014-01-09
      • 2015-06-16
      • 2014-07-27
      相关资源
      最近更新 更多