【问题标题】:Convert time_t to timeval将 time_t 转换为 timeval
【发布时间】:2015-03-22 09:53:33
【问题描述】:

我在将time_t 转换为struct timeval 时遇到问题。我需要从time_t 值中填充tv_usectv_sec 值。

为了填充tv_sectv_usec,我们需要调用gettimeofday()。但我不想调用那个函数,因为我有时间在time_t。从time_t 我想提取/转换为毫秒。由于现有代码,他们使用 struct timeval 进行填充。

如果您能建议如何从 time_t 中获取毫秒,那就太好了。

对此的任何帮助将不胜感激。 提前致谢。

【问题讨论】:

  • 你的问题不是很清楚(或者很不清楚)。如果您确实希望获得帮助,请添加您的代码。
  • 问题出在哪里? time_t 以秒为单位,timevalstruct,其中还包括微秒(因此对于 tv_sec 进行简单的转换为 int_32 就足够了)。它们之间没有任何偏移问题(1/1/1970),所以应该很简单。你有什么问题,究竟

标签: c linux gcc time


【解决方案1】:

struct timeval 的定义(在<sys/time.h> 中):

struct timeval 
{
     time_t      tv_sec;     /* seconds */
     suseconds_t tv_usec;    /* microseconds */
};

如您所见,time_t 只能保持 ,您无法从 time_t 获得 毫秒。如果您真的想使用timeval 对象,您可以简单地定义一个timeval 对象,然后手动将time_t 变量添加到它。即,

time_t time_here; //Your time_t variable.
timeval time_now; //Your timeval object.
time_now.tv_sec = time_here; //Assign time_here to this object.
time_now.tv_usec = 0; //As time_t can hold only seconds.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-18
    • 2013-03-22
    • 2014-01-16
    • 2011-03-14
    • 2013-10-24
    • 2013-06-23
    • 2015-05-06
    相关资源
    最近更新 更多