1 #include <boost/date_time/posix_time/posix_time.hpp>
2 #include <boost/date_time/gregorian/gregorian.hpp>
3 #include <iostream>
4 #include <stdint.h>
5
6 int main()
7 {
8 using namespace boost::posix_time;
9 using namespace boost::gregorian;
10
11 ptime ptNow( second_clock::local_time() );
12 std::cout << to_simple_string( ptNow ) << std::endl;
13
14 tm tm1 = to_tm( ptNow );
15 time_t tt = mktime( &tm1 );
16
17 tm* tm2 = localtime( &tt );
18
19 ptime ptt = from_time_t( tt );
20 ptime pttm = ptime_from_tm( tm1 );
21 std::cout << to_simple_string( ptt ) << "\n" << to_simple_string( pttm ) << std::endl;
22
23 return 0;
24 }
輸出結果:
2009-Sep-10 15:24:10
2009-Sep-10 07:24:10
2009-Sep-10 15:24:10
第一個為ptime獲得的當前時間的輸出。
第三個為ptime轉為tm,再tm轉成ptime的輸出
第二個為那個tm轉成time_t,time_t再轉回ptime的輸出。
從結果看,第二個輸出的時間很詭異上居然差了8個小時,難道是UTC時間?但boost doc那里沒有這個說明,只是說用from_time_t可以將time_t轉成ptime。程序中間將time_t用localtime轉回tm作驗證,結果是正確的。
詭異了……