2011-02-05 17 views
21

boost :: date_timeとstd :: chronoはどのように相互運用可能ですか?boost :: date_timeとstd :: chronoとの相互運用性

たとえば、boost :: posix_time :: ptimeとstd :: chrono :: time_pointの間で変換する方法はありますか?

このような変換に関するドキュメントを検索しようとしましたが、見つかりませんでした。

答えて

13

私はブーストでこれを見つけたがメーリングリストをコミット:ここhttp://lists.boost.org/boost-commit/2009/04/15209.php

は、関連する機能です。

template < class Clock, class Duration> 
struct convert_to<posix_time::ptime, chrono::time_point<Clock, Duration> > { 
    inline static posix_time::ptime apply(const chrono::time_point<Clock, Duration>& from) 
    { 
     typedef chrono::time_point<Clock, Duration> time_point_t; 
     typedef chrono::nanoseconds duration_t; 
     typedef duration_t::rep rep_t; 
     rep_t d = chrono::duration_cast<duration_t>(from.time_since_epoch()).count(); 
     rep_t sec = d/1000000000; 
     rep_t nsec = d%1000000000; 
     return boost::posix_time::from_time_t(0)+ 
     boost::posix_time::seconds(static_cast<long>(sec))+ 
     #ifdef BOOST_DATE_TIME_HAS_NANOSECONDS 
     boost::posix_time::nanoseconds(nsec); 
     #else 
     boost::posix_time::microseconds((nsec+500)/1000); 
     #endif 
    } 
}; 

template < class Clock, class Duration> 
struct convert_to<chrono::time_point<Clock, Duration>, posix_time::ptime> { 
    inline static chrono::time_point<Clock, Duration> apply(const posix_time::ptime& from) 
    { 
     boost::posix_time::time_duration const time_since_epoch=from-boost::posix_time::from_time_t(0); 
     chrono::time_point<Clock, Duration> t=chrono::system_clock::from_time_t(time_since_epoch.total_seconds()); 
     long nsec=time_since_epoch.fractional_seconds()*(1000000000/time_since_epoch.ticks_per_second()); 
     return t+chrono::nanoseconds(nsec); 

    } 
}; 

彼らはブーストリリースの一部になろうとしているとき、私はよく分かりません。現在、ブーストのトランクには入っていないようです...

+9

Good find。これらの関数は、Clockのエポックがptimeの:New Years、1970と同じであると仮定しているように見えます。その仮定が真であれば、これらの関数が機能します。そうでない場合、これらの関数はサイレント実行時エラーです。 –

+0

エポックが異なる場合でもこれらの関数を正しく実装できますか? – HighCommander4

+4

私はあなたがとても近づくと信じています。私は最初にカスタムクロノ::クロック(ネームスペースクロノである必要はありません)を作成して、新年、1970の時代を持ちます。上記のようにptimeと新しい時計を変換します。そして、2つのクロノクロックの間を、お互いからnow()を取得することで、近似的に変換することができます。各time_pointのtime_since_epoch()を減算して、2つのクロノクロックのエポックの差である継続時間を取得します。その差を加算または減算して、2つのクロノtime_pointsを変換します。 –

11

あなたがするとstdからのtime_tを変換することができます::クロノ:: SYSTEM_CLOCK :: time_point:

class system_clock 
{ 
public: 
    ... 
    static time_t  to_time_t (const time_point& __t); 
    static time_point from_time_t(time_t __t); 
}; 

そして、あなたはPTIMEへのtime_tを変換することができます:

ptime from_time_t(time_t t); 

しかし、私は、 ptimeをtime_tに変換する方法はありません。

+1

ブーストのto_tm(ptime)を使用してtm構造体を取得し、time.h/ctimeからmktime(...)を使用してtime_tを取得できます。 http://www.cplusplus.com/reference/ctime/mktime/ –

+1

ソフトウェアが2038年以降に実行されないようにするhttps://en.wikipedia.org/wiki/Year_2038_problem –

+0

@DarienPardinasのコメントを拡張するには32ビットLinuxプラットフォームでは、 'time_t'に32ビットの符号付き整数を使用します。これはY2038の問題につながります。 –