Michael D
Michael D

Reputation: 1479

boost local_date_time: how to set a specific time information(hour, min and sec)

I have a question which is related to different timezone. There is a file storing a local start and end time. e.g. the first entry is in NY timezone while the second is in HK timezone.

80000-150000
100000-180000

So I try to use the boost::local_date_time to get the local current time by local_sec_clock::local_time(poTimezone) where poTimezone is boost::local_time::time_zone_ptr. Then set the hour, min and sec to this new object. However, I found there is no way to set that for local_date_time object. Is there anyone who have any idea on this?

Upvotes: 2

Views: 883

Answers (1)

sehe
sehe

Reputation: 394054

The local_data_time

A sample speaks more than a thousand words I guess:

#include <boost/date_time/local_time/local_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");
    auto HK = db.time_zone_from_region("Asia/Hong_Kong");

    lt::local_date_time first (date {2015,1,1}, pt::time_duration{10,12,0}, NY, false);
    lt::local_date_time second(date {2015,1,1}, pt::time_duration{10,12,0}, HK, false);

    lt::local_time_period period(first, second);
    std::cout << "period: " << period << "\n";
    std::cout << "duration: " << period.length() << "\n";
}

Prints

period: [2015-Jan-01 10:12:00 EST/2015-Jan-01 10:11:59.999999 HKT]
duration: -13:00:00

See it Live On Coliru (without timezone database)


Bonus

Two different ways to update time fields on an existing ldt:

first  = lt::local_date_time(first.date(),  pt::hours(7) +  pt::seconds(59), first.zone(),  first.is_dst());
//
second = lt::local_date_time(second.date(), pt::time_duration(7, 0, 59),     second.zone(), second.is_dst());

See it Live as well

Upvotes: 1

Related Questions