2

I have the following function to get the seconds since epoch for midnight of the present day.

long int midnight_time()
{
  time_t t;
  struct tm *local;
  t = time(NULL);
  struct tm timeinfo;
  local = localtime(&t);
  timeinfo.tm_year = local->tm_year;
  timeinfo.tm_mon = local->tm_mon;
  timeinfo.tm_mday = local->tm_mday;
  timeinfo.tm_hour = 0;
  timeinfo.tm_min=0;
  timeinfo.tm_sec=0;
  long int midnight_epoch = mktime(&timeinfo);
  return midnight_epoch;
}

When I called this function twice in code right after each other, e.g.

cout<<midnight_time()<<endl;
cout<<midnight_time()<<endl;

I consistently get radically different results, for example: 1367816400 1367812800

This is a difference of nearly 4000 seconds. I would expect the numbers to be the same. Can anybody see what I am doing wrong?

4

3 回答 3

6

不是没有设置 tm_isdst 标志吗?差值正好是 1 小时。

于 2013-05-07T00:56:56.247 回答
2

为避免由未初始化的内存位置引起的问题(这似乎是您的情况),您应该使用函数返回指针的 tm 结构localtime。这是一个例子:

time_t midnight_time()
{
  struct tm *local;
  time_t now = time(NULL);
  local = localtime(&now);

  local->tm_hour = 0;
  local->tm_min=0;
  local->tm_sec=0;

  return mktime(local);
}

@jmihalicza 更好地回答了您的问题,这只是改进代码的建议。

于 2013-05-07T01:53:09.850 回答
1

正如@jmihalicza 答案中提到的那样,问题是您没有从结构中设置tm_isdst标志。local大概由于您的时间相差一个小时,因此您的两个结构中的标志在两次中的一个中是相反的,导致mktime生成的时间不同一小时。

但是,您可能会发现简单地取消小时、分钟和秒而不是使用mktime它更容易(尽管这在 DST 转换期间效果不佳 - 我无法从您的问题中判断这是否是您的一个因素):

return t - (timeinfo.tm_hour * 3600) - (timeinfo.tm_min * 60) - timeinfo.tm_sec;
于 2013-05-07T01:26:38.540 回答