我正在编写一个对当地时间非常敏感的软件。我正在使用 boost::posix_time 来获取计算机的本地时间。但是,我注意到如果我们在执行过程中更改时间和时区,本地时间就会完全错误。这是我写的一个小测试程序:
#include <boost/date_time/posix_time/posix_time.hpp>
#include <stdio.h>
int main(int argc, char* argv[])
{
while(1)
{
std::cout << "It's : " << boost::posix_time::to_simple_string(
boost::posix_time::second_clock::local_time()) << std::endl;
sleep(1);
}
return 0;
}
然后我启动应用程序,时间正确:
./testDate
It's : 2013-Apr-22 10:35:22
然后我在执行过程中更改了时间和时区,时间完全错了!
rm /etc/localtime ; ln -s /usr/share/zoneinfo/Europe/Belfast /etc/localtime ; date -s 10:35:00
It's : 2013-Apr-22 10:35:16
It's : 2013-Apr-22 10:35:17 <-- Time changed here
It's : 2013-Apr-22 04:35:00
It's : 2013-Apr-22 04:35:01
但是如果我手动重新启动应用程序,时间又是正确的!我想知道是否有办法告诉 boost 从系统时钟刷新日期时间?我猜它在启动时读取一次并将时间存储在内存中。我如何检测到时区或时间已更改,我必须告诉 boost 更新时间?通过定期询问时间来检查时间是否与我上次获得时间的时间有显着差异?