使用前:
#include <boost/date_time/gregorian/gregorian.hpp>
using namespace boost::gregorian;
date d; //无效的日期
date d1(2023,8,8); //使用数字构造日期
date d3(2023,Aug,8);//可使用英文指定月份
//使用工厂函数 from_string,from_undelimited_string;
date d4 = from_string("2020-12-01");
date d5 = from_undelimited_string("20230808");
cout << "year: " << d3.year() << " month: " << d3.month() << " day: " << d3.day() << endl;
//day_of_year:返回date是当年的第几天; day_of_week:返回date星期数;
cout << "day_of_week: " << d5.day_of_week() << " day_of_year: " << d5.day_of_year() << endl;
//week_number:返回date所在的周是当年的第几周;
cout << "week_number: " << d5.week_number() << endl;
//一次性获取年月日数据
date::ymd_type ymd = d1.year_month_day();
cout << "year: " << ymd.year << " month: " << ymd.month << " day: " << ymd.day << endl;
//检测是否是一个特殊日期
cout << d4.is_infinity() << endl; //是否是一个无限日期
cout << d4.is_neg_infinity() << endl; //是否是一个负无限日期;
cout << d4.is_pos_infinity() << endl;//是否是一个正无限日期;
cout << d.is_not_a_date() << endl;//是否是一个无效日期
cout << d4.is_special() << endl;//是否是任意一个特殊日期;
//date对象转字符串;
cout << to_simple_string(d1) << endl; //YYYY-mmm-DD格式,其中mmm为英文名;
cout << to_iso_string(d1) << endl; //YYYYMMDD格式
cout << to_iso_extended_string(d1) << endl;//YYYY-MM-DD数字格式
//与tm结构的互转
tm tt = to_tm(d1);
cout << tt.tm_year << " " << tt.tm_mon << " " << tt.tm_mday << endl;
date d6 = date_from_tm(tt);
cout << "year: " << d6.year() << " month: " << d6.month() << " day: " << d6.day() << endl;
//还提供了months,years,weeks; 分别表示n月,n年,n星期;
weeks w(2);
cout << w.days() << endl;
years y(5);
cout << y.number_of_years() << endl;
months m(3);
cout << m.number_of_months() << endl;
//日期区间
date_period dp(date(2023,8,8), days(12));
date_period dp1(date(2023,8,8), date(2023,9,8));
cout << dp.begin().day() << " " << dp.last().day() << " " << dp.length().days() << endl;
//判断日期区间是否在日期前或后;
cout << dp1.is_before(date(2023,6,8)) << " " << dp1.is_after(date(2023,10,8)) << endl;
//日期区间是否包含另一个
cout << dp1.contains(date(2023,8,9)) << endl;
//dp1.intersection(const period & other);//返回两个区间的交集
//dp1.intersects(const period & other);//两个日期区间是否存在交集;
//dp1.is_adjacent(const period & other);//两个日期区间是否相邻;