boost::date_time库提供了许多关于日期和时间的功能,我们先从日期学起。
1. 构造日期对象
boost::gregorian::date支持从1400-01-01到9999-12-31之间的日期。
先看默认构造:
boost::gregorian::date d;
没有入参的构造,将得到一个“非法日期”(称为 “not a date”),不能对这个日期对象进行除判断之外的大多数操作,否则将抛出一个移仓。
判断一个日期是否无效,可以调用成员函数:“is_not_a_date()”,更多情况下,构造时我们直接传入年、月、日:
boost::gregorian::date my_birthday(1974, 4, 20);
也可以通过boost提供from_XXX_string()系统工厂函数创建:
boost::gregorian::date my_birthday(1974, 4, 20);
boost::gregorian::date d1, d2, d3;
d1 = boost::gregorian::from_simple_string("1984-10-22");
d2 = boost::gregorian::from_simple_string("1984/10/22");
d3 = boost::gregorian::from_undelimited_string("20040119");
如果所提供的年月日不是合法日期时间,构造过程也将抛出异常。
另外,boost::date_time还提供了一些枚举值,方便构造特殊日期:
//相当于空构造,但意义清晰
boost::gregorian::date d_not_date
(boost::date_time::not_a_date_time);
assert(d_not_date.is_not_a_date());
//9999-12-31
boost::gregorian::date d_max
(boost::date_time::max_date_time);
//1400-01-01
boost::gregorian::date d_min
(boost::date_time::min_date_time);
//一个负无限的日期
boost::gregorian::date d_neg_infin
(boost::date_time::neg_infin);
//一个正无限的日期
boost::gregorian::date d_pos_infin
(boost::date_time::pos_infin);
配套提供is_not_a_date(),is_neg_infinity(),is_pos_infinity(),is_special()成员函数用作特殊日期判断。
程序中最常见的事,还是构造出今天。这需要使用boost::date_time中的另一个日期工厂“day_clock”,它是一个类模板,可以针对不同日期类型获得“今天”,我们只学习“公历”,所以需要使用:
boost::date_time::day_clock <boost::gregorian::date>
gregorian名字空间内已经针对公历日期类型进行定义,因此简单的写法是:
boost::gregorian::day_clock。
day_clock有两个静态成员函数可分别创建两个不同的“今天”,一个是本地日期,一个是UTC:
//本地日期
boost::gregorian::date
today_local(boost::gregorian::day_clock::local_day());
//UTC日期
boost::gregorian::date
today_utc(boost::gregorian::day_clock::universal_day());
二者的区别是本地日期带时区(比如北京时间处于东八区),和UTC有时差。
比如北京时间2019年9月20日上午8点取universzl_day,将是19号。
boost::date_time还提供诸如得到整个月份的最后一个星期天或者第一个星期一等等日期工厂,需自学。
2. 访问日期属性
如果这个日期对象是合法的,我们就可以方便的访问它的年、月、日等属性。
(编译以下工程,需要在配置中依序加入链接库:boost_date-time和boost_system。)
其中,星期几仍然从0开始,0依然表示周日。全年第几周,同样从0开始。day_of_year返回1~366。
date对象还可以帮我们查看一个月结束在哪一天。所提供的“end_of_month()”函数,将返回另一个date对象,表示该月的最后一天,如果想知道2013年2月的最后一天是哪天,我们再补上两行代码测试:
【小提示】:判断闰年
上述代码演示了判断闰年的一种方法,不过boost::date_time库有更简便的函数:
date还内嵌一个结构(实际是类型别名):ymd_type,以及对应的year_month_day()成员,用于一次性获得年月日数据: