Duration Algorithm in C ++

I am making a program that requires a duration (in time_t) of a year.

In other words, time_tfor DD / MM / YYYY + duration = time_tfor DD / MM / YYYY + 1

Thus, this may not always be 365 days (and 02/29/2012 will become 02/28/2013)

Here is the algorithm I came with:

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

Here is the day 60 * 60 * 24 seconds

This algorithm works. But I was wondering if there is another way to do this without all the conditions and only 2 possible return values ​​or just a "trick" to optimize this thing.

I tried to zoom tm_yearin struct tmas follows:

// 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;

But the result is not what I want, I got -1 hour or -25 ...

I guess, because the year is not exactly 365 * 24 * 60 * 60.

+5
3

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;

}

, posix_time Boost:

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(), , .

+5
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

:

if (YEAR is leap)
    if (< 29th Feb) return 365+1
    if (= 29th Feb) return 365-1
else if (YEAR+1 is leap)
    if (> 29th Feb) return 365+1

return 365

? , "".

@betabandido, - date(year+1, mon, day) - date(year, mon, day) , , 11 .

+2

. , . , " , 4, 100, , 400.

, , . 365,2422 spring 365,2424 .

( ) .

0

All Articles