我想知道如何使用Boost和C++在纽约准确地计算当地时间,即使我在位于不同国家的服务器上运行代码?如何在纽约使用C++和Boost查找当地时间?
我已经试过
我已经试过看Boost C++ examples,但我似乎无法找到任何东西。
我想知道如何使用Boost和C++在纽约准确地计算当地时间,即使我在位于不同国家的服务器上运行代码?如何在纽约使用C++和Boost查找当地时间?
我已经试过
我已经试过看Boost C++ examples,但我似乎无法找到任何东西。
对于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
非常酷的c + + 11版本。谢谢! –
完美答案!我已经将它标记为最佳答案。 – Contango
首先,你需要获得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";
要将其转换为NY时间,只定义了local_adjustor你的时区,并从它呼叫utc_to_local
。
如何定义'us_dst'?我似乎无法找到关于此的文档。不推动支持像“America/New_York”这样的IANA区域? –
这是'boost :: posix_time'命名空间中的typedef。它在'posix_time_types.hpp'中定义。 具体来说,''typedef date_time :: us_dst_rules
啊,那么它只知道美国DST的* current *规则。最好使用IANA TZDB。 [看起来可以做到这一点](http://www.boost.org/doc/libs/1_54_0/doc/html/date_time/local_time.html#date_time.local_time.tz_database)。一个例子[这里](http://www.boost.org/doc/libs/1_54_0/doc/html/date_time/examples.html#date_time.examples.seconds_since_epoch)。虽然这是UTC和OP的本地通缉相反。 –
您需要做的不仅仅是看例子。你是否仔细阅读过文档? –
@Lightness在轨道中的比赛公平点,我正在阅读文档。 – Contango
你可能会发现这个有趣的http://home.roadrunner.com/~hinnant/date_algorithms.html – pyCthon