c++ - C++中的年持续时间算法

标签 c++ algorithm duration

我正在制作一个需要一年持续时间(time_t)的程序。

换句话说,time_t of DD/MM/YYYY + duration = time_t of DD/MM/YYYY+1

所以它可能并不总是 365 天(29/02/2012 将变为 28/02/2013)

这是我附带的算法:

if YEAR is leap than
    if we are before the 29th feb' than return 365+1 days
    else if we are the 29th feb' than return 365-1 days
    else return 365 days
else if YEAR+1 is leap than
    if we are before or the 28th feb' than return 365 days
    else return 365+1 days
else return 365 days

在这里,一天是 60 * 60 * 24 秒

这个算法似乎可行。但我想知道是否有另一种方法可以在没有所有这些条件且只有 2 个可能的返回值的情况下执行此操作,或者只是一些“技巧”来优化事情。

我尝试从 struct tm 中增加 tm_year ,如下所示:

// t is the input time_t
struct tm Tm (*localtime(&t));
if (Tm.tm_mon == 2 && Tm.tm_mday == 29) --Tm.tm_mday;
++Tm.tm_year;
return mktime(&Tm) - t;

但是结果不是我想要的,我得到了-1小时,或者-25...

我猜这是因为一年不完全是 365 * 24 * 60 * 60。

最佳答案

我会使用 Boost为此,因为它已经实现了您正在寻找的东西:

#include <iostream>
#include <boost/date_time/gregorian/gregorian_types.hpp>
namespace date = boost::gregorian;

int main() {
   date::date_period dp(date::date(2012, 6, 4), date::date(2013, 6, 4));
   long days = dp.length().days();
   std::cout << "Days between dates: " << days << std::endl;

如果您想要更精确,那么您也可以使用 Boost 中的 posix_time:

namespace ptime = boost::posix_time;

...

ptime::ptime t1(date::date(2012, 6, 4), ptime::hours(0));
ptime::ptime t2(date::date(2013, 6, 4), ptime::hours(0));

ptime::time_duration td = t2 - t1;
std::cout << "Milliseconds: " << td.total_milliseconds() << std::endl;

通常 time_t 以秒为单位。因此,您只需调用 td.total_seconds() 即可获得您要查找的值。

关于c++ - C++中的年持续时间算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10878090/

相关文章:

群体尺度算法

kotlin - 几周而不是几天

jQuery 设置默认全局缓动和队列

c++ - 将 float 的高度图数组导出为 16 位原始格式

c++ - Visual C++ 中的 CreateWindow() 始终返回 null

c++ - 指向多态类层次结构中派生类型的智能指针,编译错误

android - 获取Android音频文件的持续时间

c++ - QGraphicsPixmapItem 不可选

ruby - 使用二维数组中的最大元素数查找非空交集

c++ - set_difference、set_intersection 和 set_union 的就地版本