问题
What is the appropriate way to work with the the postgresql datatype "timestamp without timezone" from c++ (libpqxx)? I haven't been able to find a way to do this yet. I am restricted to the "timestamp without timezone" datatype in the postgresql and the environment is running utc time. I was hoping to find a mapping to a std::chrono::system_clock::time_point member but I can't find a such in libpqxx.
//s has a time_point var and r is a pqxx::result, r[0] is sensible
s.creationtime = r[0]["creationtime"].as<std::chrono::system_clock::time_point>();
回答1:
With help from boost:
s.creationtime = makeTimePoint(r[0]["creationtime"].as<string>());
makeTimePoint:
std::chrono::system_clock::time_point makeTimePoint(const std::string& s)
{
using namespace boost::posix_time;
using namespace std::chrono;
const ptime ts = time_from_string(s);
auto seconds = to_time_t(ts);
time_duration td = ts.time_of_day();
auto microseconds = td.fractional_seconds();
auto d = std::chrono::seconds{seconds} + std::chrono::microseconds{microseconds};
system_clock::time_point tp{duration_cast<system_clock::duration>(d)};
return tp;
}
回答2:
The C++20 spec introduces a family of chrono::time_point
s called local_time:
// [time.clock.local], local time
struct local_t {};
template<class Duration>
using local_time = time_point<local_t, Duration>;
using local_seconds = local_time<seconds>;
using local_days = local_time<days>;
These time_point
s represent a "timestamp without a timezone".
There exists a free, open-source preview of this C++20 library here:
https://github.com/HowardHinnant/date
which is currently in use by other projects around the globe. This library has a few minor changes from the C++20 spec, such as putting everything in namespace date
instead of namespace std::chrono
.
Example program using this library:
#include "date/date.h"
#include <iostream>
int
main()
{
using namespace date;
using namespace std::chrono;
int y = 2019;
int m = 8;
int d = 28;
int H = 14;
int M = 42;
int S = 16;
int US = 500'000;
local_time<microseconds> lt = local_days{year{y}/m/d} + hours{H} +
minutes{M} + seconds{S} + microseconds{US};
std::cout << lt << '\n';
}
Output:
2019-08-28 14:42:16.500000
来源:https://stackoverflow.com/questions/57694237/postgresql-timestamp-to-stdchrono-value