Boost.DateTimeでUTCとLocalの変換
posix_time::ptimeのutc <-> local変換。
utc to local
変換方法2種。1つ目はC言語関数ラッパーを使うもの。これはutc -> localのみの変換。通常はこれだけで事足りそう。
#include <boost/date_time/c_local_time_adjustor.hpp> date_time::c_local_adjustor<posix_time::ptime> adj1; posix_time::ptime t1 = adj1.utc_to_local(now);
もう一つはオフセットとサマータイムを自前で設定して、変換器を用意する。
#include <boost/date_time/local_time_adjustor.hpp> date_time::local_adjustor<posix_time::ptime, 9, posix_time::no_dst> adj2; posix_time::ptime t2 = adj2.utc_to_local(now);
local to utc
上記2つ目のdate_time::local_adjustorは逆の変換にも使える。
#include <boost/date_time/local_time_adjustor.hpp> date_time::local_adjustor<posix_time::ptime, 9, posix_time::no_dst> adj2; posix_time::ptime t3 = adj2.local_to_utc(t2);
サンプル
現在のUTCを取得してそれぞれ変換してみる。
#include <iostream> #include <boost/date_time.hpp> #include <boost/date_time/c_local_time_adjustor.hpp> #include <boost/date_time/local_time_adjustor.hpp> int main(const int argc, const char * const argv[]) { using namespace boost; posix_time::ptime now = posix_time::second_clock::universal_time(); // utc to local 1 date_time::c_local_adjustor<posix_time::ptime> adj1; posix_time::ptime t1 = adj1.utc_to_local(now); // utc to local 2 date_time::local_adjustor<posix_time::ptime, 9, posix_time::no_dst> adj2; posix_time::ptime t2 = adj2.utc_to_local(now); // local to utc posix_time::ptime t3 = adj2.local_to_utc(t2); // out std::cout << now << std::endl; std::cout << t1 << std::endl; std::cout << t2 << std::endl; std::cout << t3 << std::endl; return 0; }