コードの書きぶりのメモです。
boost::posix_time::ptime の使い方の学習用にも使えますが、再利用できそうだったらご自由にお使いください。
ptime-util.h
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/date_time/c_local_time_adjustor.hpp>
#include <boost/date_time/local_time/local_time.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
// boost::posix_time::ptime と エポックからの秒数(int64_t) との変換
int64_t PosixTimeToSeconds(boost::posix_time::ptime t)
{
boost::posix_time::ptime epoch(boost::gregorian::date(1970, 1, 1));
int64_t result = (t - epoch).total_seconds();
return result;
}
boost::posix_time::ptime SecondsToPosixTime(int64_t n)
{
boost::posix_time::ptime result(boost::gregorian::date(1970, 1, 1),
boost::posix_time::seconds(n));
return result;
}
// boost::posix_time::ptime と エポックからのミリ秒数(int64_t) との変換
int64_t PosixTimeToMilliSeconds(boost::posix_time::ptime t)
{
boost::posix_time::ptime epoch(boost::gregorian::date(1970, 1, 1));
int64_t result = (t - epoch).total_milliseconds();
return result;
}
boost::posix_time::ptime MilliSecondsToPosixTime(int64_t n)
{
boost::posix_time::ptime result(boost::gregorian::date(1970, 1, 1),
boost::posix_time::milliseconds(n));
return result;
}
// boost::posix_time::ptime のローカルタイム/UTCタイムの変換
boost::posix_time::ptime LocalToUtc(boost::posix_time::ptime t)
{
boost::posix_time::ptime utc =
boost::posix_time::second_clock::universal_time();
boost::posix_time::ptime local = boost::date_time::c_local_adjustor<
boost::posix_time::ptime>::utc_to_local(utc);
boost::posix_time::time_duration diff = (utc - local);
return t + diff;
}
boost::posix_time::ptime UtcToLocal(boost::posix_time::ptime t)
{
boost::posix_time::ptime utc =
boost::posix_time::second_clock::universal_time();
boost::posix_time::ptime local = boost::date_time::c_local_adjustor<
boost::posix_time::ptime>::utc_to_local(utc);
boost::posix_time::time_duration diff = (local - utc);
return t + diff;
}
// boost::posix_time::ptime を 2023-04-10T07:01:45.015000 のような形式に変換
std::string PtimeToString(const boost::posix_time::ptime &t)
{
return boost::posix_time::to_iso_extended_string(t);
#if 0
std::stringstream ss;
ss.imbue(
std::locale(std::locale::classic(),
new boost::posix_time::time_facet("%Y-%m-%dT%H:%M:%S.%f")));
ss << t;
return ss.str();
#endif
}
// boost::posix_time::ptime を 2023-04-10T07:01:45.015000 のような形式から変換
boost::posix_time::ptime StringToPtime(const std::string &s)
{
return boost::posix_time::from_iso_extended_string(s);
}