考虑夏令时的时差

Get time difference with DST considered

本文关键字:时差 夏令时      更新时间:2023-10-16

我正在使用Boost。Date_time获取两个日期之间的时间差。我希望代码在这些天内也考虑夏令时的变化,并给我正确的间隔。

考虑这个例子。2015年11月1日,美国的夏时制将会改变。2点时,时钟将拨回1点。下面代码的输出没有反映这一点。它给出了23小时的差值。

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

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

在boost中是否有一种方法可以在此场景中指定DST需求?

您应该使用本地时间:

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";
}

打印:

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