示例代碼如下:
1 #include <boost/date_time/gregorian/gregorian.hpp> 2 #include <boost/date_time/posix_time/posix_time.hpp> 3 using namespace boost::gregorian; 4 using namespace boost::posix_time; 5 #include <iostream> 6 using namespace std; 7 #include <string> 8 9 void TimerTest() 10 { 11 { 12 // 例1. 日期計算:打印今天日期;今年感恩節(11月的第4個星期四)的日期;如果還沒有到今年感恩節,打印今天到感恩節還有多少天; 13 typedef nth_day_of_the_week_in_month nth_dow; 14 date today = day_clock::local_day(); // today; // 獲取今天日期; 15 std::cout << "today is: " << today << std::endl; 16 nth_dow fourth_thur_in_nov(nth_dow::fourth, Thursday, Nov); // 4th thursday in Nov; 17 date thanksgiving = fourth_thur_in_nov.get_date(today.year()); // get the date this year; 18 std::cout << "Thanksgiving day this year is: " << thanksgiving << std::endl; 19 if(today < thanksgiving) 20 { 21 date_duration dd = thanksgiving - today; // date duration; // 時間差; 22 std::cout << "has " << dd.days() << " days to thanksgiving."<< std::endl; 23 } 24 } 25 26 { 27 // 日期操作; 28 std::cout << std::endl << std::endl; 29 date today = day_clock::local_day(); // today; // 獲取今天日期; 30 std::cout << today.year() << std::endl; // 打印年; 31 std::cout << today.month() << std::endl; // 打印月; 32 std::cout << today.day() << std::endl; // 打印日; 33 std::cout << today.week_number() << std::endl; // 今年的第幾周; 34 std::cout << today.day_of_week() << std::endl; // 打印星期幾; 35 std::cout << today.day_of_year() << std::endl; // 打印一年中的第幾天; 36 std::cout << today.end_of_month() << std::endl; // 打印本月的最后一天是,閏月的2月,可以試試; 37 std::cout << today.modjulian_day() << std::endl; 38 std::cout << today.julian_day() << std::endl; 39 std::cout << (today.day_of_week() == 0) << std::endl; // 判斷今天是星期日嗎,周日為0; 40 std::cout << (today.end_of_month() == today) << std::endl; // 判斷今天是當月的最后一天嗎; 41 date dateTemp = from_string("2016-11-26"); 42 date_duration dd = dateTemp - today; // 時間差; 43 std::cout << "subDate = " << dd.days() << std::endl; // 相差多少天; 44 // 獲取指定(11月的第4個星期四)日期; 45 typedef nth_day_of_the_week_in_month nth_dow; 46 nth_dow fourth_thur_in_nov(nth_dow::fourth, Thursday, Nov); // 4th thursday in Nov; 47 date thanksgiving = fourth_thur_in_nov.get_date(today.year()); // get the date this year; 48 } 49 50 { 51 // 時間操作; 52 ptime timeTemp = second_clock::local_time(); // 獲取當前時間,秒級別; 53 std::cout << timeTemp.time_of_day() << std::endl; // 當前時間; 54 std::cout << timeTemp.date() << std::endl; // 當前時間對應的日期; 55 ptime destTime = time_from_string("2016-06-15 17:00:00"); 56 time_duration tt = timeTemp - destTime; // 時間差; 57 std::cout << "subTime = " << (tt.seconds() >= 0) << std::endl; // 相差多少秒; 58 } 59 }