【问题标题】:Boost::gregorian and leap yearsBoost::gregorian 和闰年
【发布时间】:2014-05-26 19:03:03
【问题描述】:

我正在编写一个仅使用 boost 库作为先决条件的代码。

我需要一个类来处理日期时间值和操作(加减年、月、小时等),所以我选择了公历日期作为选项。

但是,当我处理闰年的日子时,会出现一些惊喜。有一段示例代码:

int main()
{
  boost::gregorian::date d1(2000,1,1);
  boost::gregorian::days ds(118);

  boost::gregorian::date d2 = d1 + ds;

  std::cout << boost::gregorian::to_iso_extended_string(d1) << std::endl;
  std::cout << boost::gregorian::to_iso_extended_string(d2) << std::endl;

  return 0;
}

Output:
2000-01-01
2000-04-28 (should be 2000-04-27)

是否有解决此问题的选项?在手册页中,关于“导致意外结果...”的提升警告

【问题讨论】:

  • 为什么结果应该是4月27日? 2000 年 1 月 1 日之后的 118 天是 2000 年 4 月 28 日。
  • 其实你的答案是正确的。我们测试的代码用于在 datetime 中执行额外的操作并减去一天,以进行舍入,谢谢。

标签: c++ datetime boost


【解决方案1】:

我认为它是正确的:

for a in {1..118}; do echo -n "+$a days: "; date --rfc-2822 -d"2000-01-01 +$a days"; done

打印

表明我在闰日前后没有发现异常情况:

+1 days: Sun, 02 Jan 2000 00:00:00 +0100
+2 days: Mon, 03 Jan 2000 00:00:00 +0100
...
+57 days: Sun, 27 Feb 2000 00:00:00 +0100
+58 days: Mon, 28 Feb 2000 00:00:00 +0100
+59 days: Tue, 29 Feb 2000 00:00:00 +0100
+60 days: Wed, 01 Mar 2000 00:00:00 +0100
...
+116 days: Wed, 26 Apr 2000 00:00:00 +0200
+117 days: Thu, 27 Apr 2000 00:00:00 +0200
+118 days: Fri, 28 Apr 2000 00:00:00 +0200

【讨论】:

  • 其实你的答案是正确的。我们测试的代码用于在 datetime 中执行额外的操作并减去一天,以进行舍入,谢谢。
猜你喜欢
  • 1970-01-01
  • 2016-10-25
  • 1970-01-01
  • 2017-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多