boost 日期时间计算
Posted 晴天224
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了boost 日期时间计算相关的知识,希望对你有一定的参考价值。
示例代码如下:
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 }
以上是关于boost 日期时间计算的主要内容,如果未能解决你的问题,请参考以下文章