Reputation: 47875
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.
Upvotes: 0
Views: 1001
Reputation: 218700
You could use this preview of the C++20 <chrono>
facilities, which works with 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();
}
The trick with this library is to use %Ez
in place of %z
.
This library does require some installation.
Upvotes: 2