我有一个SQL server数据库,我正在从其中提取日期,并将timestamp_t类型转换为Int64:
Int64 from_timestamp_t(dtl::timestamp_t& t)
{
// create a new posix time structure
boost::posix_time::ptime pt
(
boost::gregorian::date ( t.year, t.month, t.day),
boost::posix_time::time_duration ( t.hour, t.minute, t.second, t.fraction )
);
ptime epoch(date(1970, Jan, 1));
boost::posix_time::time_duration fromEpoch = pt - epoch;
// return it to caller
return fromEpoch.total_milliseconds();
}
我尝试从Int64转换回boost ptime,如下所示:
ptime from_epoch_ticks(Int64 ticksFromEpoch)
{
ptime epoch(date(1970, Jan, 1), time_duration(0,0,0));
ptime time = epoch + boost::posix_time::milliseconds(ticksFromEpoch);
return time;
}
由于某些原因,我不知道为什么,我的日期、时间等都是正确的,但我的分钟比它们应该的时间提前了几分钟。是因为数据库中的时间戳是以秒为单位的,而我使用的是毫秒吗?我该如何解决这个问题?
按照Dan的建议应用以下修改似乎已经解决了这个问题:
Int64 from_timestamp_t(dtl::timestamp_t& t)
{
int count = t.fraction * (time_duration::ticks_per_second() % 1000);
boost::posix_time::ptime pt
(
boost::gregorian::date ( t.year, t.month, t.day ),
boost::posix_time::time_duration ( t.hour, t.minute, t.second, count )
);
ptime epoch(date(1970, Jan, 1), time_duration(0, 0, 0, 0));
boost::posix_time::time_duration fromEpoch = pt - epoch;
return fromEpoch.total_milliseconds();
}
发布于 2011-09-14 20:27:30
我对SQL Server2005不太熟悉,但是如果ticksFromEpoch等于一秒,那么boost posix time就有秒数功能。
ptime time = epoch + boost::posix_time::seconds(ticksFromEpoch);
但是,boost date_time documentation中提供了处理此问题的通用方法
处理这个问题的另一种方法是利用time_duration的ticks_per_second()方法来编写可移植的代码,而不管库是如何编译的。计算与分辨率无关的计数的一般公式如下:
count*(time_duration_ticks_per_second / count_ticks_per_second)
例如,让我们假设我们想要使用一个表示十分之一秒的计数来构造
。也就是说,每个刻度是0.1秒。
int number_of_tenths = 5; // create a resolution independent count --
// divide by 10 since there are
//10 tenths in a second.
int count = number_of_tenths*(time_duration::ticks_per_second()/10);
time_duration td(1,2,3,count); //01:02:03.5 //no matter the resolution settings
https://stackoverflow.com/questions/7413820
复制相似问题