【问题标题】:boost ptime from sql server timestamp_t is off by minutes. What did I do wrong?从 sql server timestamp_t 提升 ptime 以分钟为单位。我做错了什么?
【发布时间】:2011-09-14 09:05:12
【问题描述】:

我有一个 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();
}

【问题讨论】:

  • 丹的回答成功了,我在上面修改了我的解决方案

标签: c++ sql-server-2005 boost-date-time dtl-cpp


【解决方案1】:

我不熟悉 SQL Server 2005,但是如果 ticksFromEpoch 等于一秒,则 boost posix time 具有 seconds 功能。

ptime time = epoch + boost::posix_time::seconds(ticksFromEpoch);

但是,处理此问题的通用方法在 boost date_time documentation 中提供:

另一种处理方法是利用 ticks_per_second() 方法 的 time_duration 来编写可移植的代码,无论如何 库被编译。计算分辨率的一般公式 独立计数如下:

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

【讨论】:

  • 我发现,如果我先转换为 time_t,然后使用 from_time_t 转换为 ptime,然后返回 total_milliseconds,就像它正确出现之前一样。从 gregorian 和 time_duration 构造我的 posix_time 肯定有问题,但我仍然看不到它。
猜你喜欢
  • 1970-01-01
  • 2015-01-15
  • 2010-12-24
  • 2011-04-16
  • 2012-10-23
  • 1970-01-01
  • 2014-09-24
  • 2016-05-14
  • 1970-01-01
相关资源
最近更新 更多