如何使用C++和Boost在纽约找到当地时间?

Con*_*ngo 1 c++ timezone boost

我想知道如何使用Boost和C++准确计算出纽约当地时间,即使我在不​​同国家/地区的服务器上运行代码?

我试过了什么

我试过看Boost C++示例,但我似乎找不到任何东西.

Ray*_*der 6

对于OP,以及想要查看tz数据库的Matt Johnson.

#include "boost/date_time/posix_time/posix_time.hpp"
using namespace boost::posix_time;
using namespace boost::gregorian;
#include "boost/date_time/local_time/local_time.hpp"

// form an empty database
boost::local_time::tz_database tz_database;
// load the time zone database which comes with boost
tz_database.load_from_file( "../../boost/libs/date_time/data/date_time_zonespec.csv" ); 

// obtain a specific time zone from the database
boost::local_time::time_zone_ptr tzNewYork;
tzNewYork = tz_database.time_zone_from_region("America/New_York");

// example universal/local conversion (from boost example code)
// ptime now = boost::posix_time::microsec_clock::universal_time();
ptime now(date(2004,Nov,5), hours(10));
boost::local_time::local_date_time ny(now, tzNewYork );
ny.utc_time();  // 10am 2004-Nov-5
ny.local_time();  // 5am 2004-Nov-5
Run Code Online (Sandbox Code Playgroud)


Ren*_*ani 5

首先,您需要获取 UTC 时间:您可以使用boost::posix_time::second_clock::universal_time().

从你刚刚给的链接:

    //eastern timezone is utc-5
    typedef boost::date_time::local_adjustor<ptime, -5, us_dst> us_eastern;
    // ...
    ptime t3 = us_eastern::utc_to_local(t2);//back should be the same
    std::cout << to_simple_string(t2) << " UTC is " 
          << to_simple_string(t3) << " New York time "
          << "\n\n";
Run Code Online (Sandbox Code Playgroud)

要将其转换为纽约时间,只需为您的时区定义一个 local_adjustor,并utc_to_local从中调用。