CuriousMind
CuriousMind

Reputation: 21

Get time difference with DST considered

I am using Boost.Date_time to get the time difference between two dates. I want the code to consider DST change as well during these days and give me the correct interval.

Consider this example. On 1-Nov-2015, the DST is going to change in USA. At 2:00 hours, the clock will be moved back to 1:00. The output of the below code doesn't reflect that. It gives 23 hours as the difference.

date d1(2015, 11, 1);
ptime nov1_00(d1, hours(0));
ptime nov1_23(d1, hours(23));
seconds = (nov1_23 - nov1_00).total_seconds();

Output:

2015-Nov-01 00:00:00. 2015-Nov-01 23:00:00. Seconds: 82800

Is there a way in boost to specify the DST requirement in this scenario?

Upvotes: 2

Views: 126

Answers (1)

sehe
sehe

Reputation: 392911

You should be using local times:

Live On Coliru

#include <boost/date_time/local_time/local_time.hpp>
#include <boost/date_time/local_time/local_date_time.hpp>
#include <boost/date_time/local_time/local_time_io.hpp>
#include <boost/make_shared.hpp>
#include <iostream>

int main() {
    namespace lt = boost::local_time;
    namespace pt = boost::posix_time;
    using   date = boost::gregorian::date;

    lt::tz_database db;
    db.load_from_file("/home/sehe/custom/boost/libs/date_time/data/date_time_zonespec.csv");

    //for (auto region : db.region_list()) std::cout << region << "\n";

    auto NY = db.time_zone_from_region("America/New_York");

    date const d1(2015, 11, 1);

    lt::local_date_time nov1_00(d1, pt::hours(0),  NY, true);
    lt::local_date_time nov1_23(d1, pt::hours(23), NY, false);

    lt::local_time_period period(nov1_00, nov1_23);

    std::cout << "period: "   << period          << "\n";
    std::cout << "duration: " << period.length() << "\n";

    // if you insist:
    auto seconds = (nov1_23 - nov1_00).total_seconds();
    std::cout << "seconds: " << seconds << "\n";
}

Prints:

period: [2015-Nov-01 00:00:00 EDT/2015-Nov-01 22:59:59.999999 EST]
duration: 24:00:00
seconds: 86400

Upvotes: 2

Related Questions