如何使用C++和Boost查找纽约当地时间

How to find local time in New York, using C++ and Boost?

本文关键字:查找 纽约 当地时间 Boost 何使用 C++      更新时间:2023-10-16

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

我尝试过的

我试过看Boost C++的例子,但似乎什么都找不到。

对于OP,以及Matt Johnson,他希望查看正在使用的tz数据库。

#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

首先,您需要获得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 "
          << "nn";

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