jeudi 10 septembre 2020

How to get UTC offset (timezone) in correct format?

I have code like this that converts an Epoch timestamp into GMT timestamp:

#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();
}

This works fine, except that my timestamp is e.g.:

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

I'd like it to be:

2020-09-10T20:53:10+03:00

How can I do this out-of-the-box without an ugly and error-prone hack on the resulting string? I don't see any other options to get the offset besides %z.

Some other library like Boost would also be acceptable.

Aucun commentaire:

Enregistrer un commentaire