将Boost Ptime转换为EST UTC-5:00

Convert Boost Ptime To EST UTC-5:00

本文关键字:UTC-5 EST Boost Ptime 转换      更新时间:2023-10-16

我使用以下代码获取当前日期时间(山地时间)

const boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
    //In mountain time I get now = 2013-Apr-08 20:44:22

现在我使用以下方法进行转换

ptime FeedConnector::MountaintToEasternConversion(ptime coloTime) 
{
      return boost::date_time::local_adjustor <ptime, -5, us_dst>::utc_to_local(coloTime);
} 

//这个函数应该给我纽约的时间(东部标准时间),我得到的是

2013-Apr-08 16:44:22

这次错了,有什么建议吗?

据我所知,wrong time意味着它与预期有一个小时的差异,即-4小时而不是预期的-5小时。如果是,那么问题是us_std类型被指向local_adjustor声明的最后一个参数。如果指定no_dst而不是use_dst。代码运行正常,误差为-5小时。下面的代码演示了它(链接到在线编译版本)

#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/local_time_adjustor.hpp>
#include <iostream>
int main(void) {
   const boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
   const boost::posix_time::ptime adjUSDST = boost::date_time::local_adjustor<boost::posix_time::ptime, -5, boost::posix_time::us_dst>::utc_to_local(now);
   const boost::posix_time::ptime adjNODST = boost::date_time::local_adjustor<boost::posix_time::ptime, -5, boost::posix_time::no_dst>::utc_to_local(now);
   std::cout << "now: " << now << std::endl;
   std::cout << "adjUSDST: " << adjUSDST << std::endl;
   std::cout << "adjNODST: " << adjNODST << std::endl;
   return 0;
}