从午夜到日期时间的秒数

时间:2012-10-12 12:38:16

标签: c++ qt datetime utc

我将雷达数据作为"跟踪"并且轨迹数据显示自上一个午夜以来的UTC秒数。这不是自1970年1月1日以来的秒数。

现在我想将其转换为日期时间,因为知道计算机上的时钟可能与雷达上的时钟略微不同步。我假设雷达的秒是参考,而不是计算机。 我想将这些秒转换为完整的日期时间。事情似乎有点棘手 午夜。

有什么建议吗?我有一些想法,但我不想错过任何东西。

我正在使用C ++ Qt。

2 个答案:

答案 0 :(得分:1)

//  Function to extend truncated time, given the wall time and period, all
//  in units of seconds.
//
//  Example: Suppose the truncated period was one hour, and you were
//  given a truncated time of 25 minutes after the hour. Then:
//
//  o Actual time of 07:40:00 results in 07:25:00 (07:40 + -15)
//  o Actual time of 07:10:00 results in 07:25:00 (07:10 + +15)
//  o Actual time of 07:56:00 results in 08:25:00 (07:56 + +29)

double extendTruncatedTime(double trunc, double wall, int period) {
   return wall + remainder(trunc - wall, period);
}

#define extendTruncatedTime24(t) extendTruncatedTime(t, time(0), 24 * 60 * 60)

一些评论:

  • wall的单位是秒,但其基数可以是任意的。在Unix中,它通常从1970年开始。

  • 闰秒与此无关。

  • #include <math.h>需要remainder()

  • 根据OP的要求,period中的extendTruncatedTime()几乎总是二十四小时,即24 * 60 * 60。也就是说,考虑到一天中的时间,它会根据“墙”时间通过添加年,月和日来扩展它。

  • 我之前声明中唯一的例外是,因为你提到雷达,是在Asterix CAT 1数据项I001 / 141中,其中周期是512秒,其中extendTruncatedTime()为给定不太有用。

  • 还有另一个extendTruncatedTime()没有涵盖的重要案例。假设您被截断的时间包括月,小时和分钟的日期。你怎么能填写这一年和一个月?

以下代码段将年份和月份添加到从DDHHMM格式派生的时间:

time_t extendTruncatedTimeDDHHMM(time_t trunc, time_t wall) {
   struct tm retval = *gmtime_r(&trunc, &retval);
   struct tm now    = *gmtime_r(&wall,  &now);
   retval.tm_year = now.tm_year;
   retval.tm_mon  = now.tm_mon;
   retval.tm_mon += now.tm_mday - retval.tm_mday >  15; // 15 = half-month
   retval.tm_mon -= now.tm_mday - retval.tm_mday < -15;
   return timegm(&retval);
}

如上所述,这不会处理错误的输入。例如,如果今天是7月4日,那么非荒谬的310000将被悄然转换为7月1日。 (这可能是一个功能,而不是一个错误。)

答案 1 :(得分:0)

如果你可以链接另一个lib,我建议使用boost::date_time

似乎你想从午夜(纪元)以秒为单位获取当前日期,然后将雷达时间添加到它,然后将总和转换回日期时间,并将其转换为字符串。

使用boost可以帮助您:

  • 获得正确的当地时间
  • 计算日期
  • 将漂移纳入计算
  • 考虑闰秒

因为您可以使用时间间隔和持续时间等概念。您可以使用(来自增强示例):

ptime t4(date(2002,May,31), hours(20)); //4 hours b/f midnight NY time
ptime t5 = us_eastern::local_to_utc(t4);
std::cout << to_simple_string(t4) << " in New York is " 
          << to_simple_string(t5) << " UTC time "
          << std::endl;

如果你想手动计算漂移,你可以轻松地进行数学时间,类似于这样的结构:

 ptime t2 = t1 - hours(5)- minutes(4)- seconds(2)- millisec(1);
相关问题