我有一个 SQL 服务器数据库,我从中提取日期并将 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();
}