在boost中比较不同时区的时间

comparing times from different timezone in boost

本文关键字:时区 时间 boost 比较      更新时间:2023-10-16

我有一个服务器,它从几个设备收集信息。每个设备与服务器位于不同的时区。我希望将服务器的时间与设备发送服务器的时间进行比较。1.设备如何获取包括时区在内的当前时间(这将发送到服务器)?2.服务器如何将其本地时间与服务器提供的时间进行比较?

您可以使用Boost date_time库,该库已做好处理时区的充分准备。您的代码可能类似于:

// The device will collect the time and send it to the server
// along its timezone information (e.g., US East Coast)
ptime curr_time(second_clock::local_time());
// The server will first convert that time to UTC using the timezone information.
// Alternatively, the server may just send UTC time.
typedef boost::date_time::local_adjustor<ptime, -5, us_dst> us_eastern;
ptime utc_time = us_eastern::local_to_utc(curr_time);
// Finally the server will convert UTC time to local time (e.g., US Arizona).
typedef boost::date_time::local_adjustor<ptime, -7, no_dst> us_arizona;
ptime local_time = us_arizona::utc_to_local(utc_time);
std::cout << to_simple_string(local_time) << std::endl;

为了处理DST,您需要在本地调整器定义期间手动指定它(示例代码中的us_easternus_arizona)。美国包括夏令时支持,但您可以使用夏令时实用程序处理其他国家/地区的夏令时(不过,您需要根据每个国家/地区定义夏令时规则)。