Unix时间转换为可比时间

时间:2014-05-04 00:58:21

标签: c++ time unix-timestamp

我有unixtime字符串,我想按小时和分钟比较它们。

例如:

unixtime1 =“1327418725” unixtime2 =“1327511595”

time_t convertUnixToTime(const char* unixtime){

time_t time = (time_t)atol(unixtime);
return time;
}

我使用这样的功能:

time_t time1 = convertUnixToTime("1327418725");
struct tm *timeinfo1;
timeinfo1 = localtime(&time1);

time_t time2 = convertUnixToTime("1327511595");
struct tm *timeinfo2;
timeinfo2 = localtime(&time2);

cout << "time: " << asctime(timeinfo1);// << endl;
cout << "time: " << asctime(timeinfo2);// << endl;

我得到了输出:

time: Wed Jan 25 09:13:15 2012
time: Wed Jan 25 09:13:15 2012

我无法弄清楚为什么我会得到相同的时间,而且我希望能够看到difftime(),看看它们分开了多少HOURS和MINUTES。

有任何建议/见解吗?

1 个答案:

答案 0 :(得分:1)

localtime()返回指向库的整数对象的指针。您将此指针存储在timeinfo1和timeinfo2中两次。

您需要复制struct tm

#include <ctime>
#include <cstdlib>
#include <iostream>

time_t convertUnixToTime(const char* unixtime){

  time_t time = (time_t)atol(unixtime);
  return time;
}


using namespace std;

int main()
{
  time_t time1 = convertUnixToTime("1327418725");
  struct tm timeinfo1;
  timeinfo1 = *localtime(&time1);

  time_t time2 = convertUnixToTime("1327511595");
  struct tm timeinfo2;
  timeinfo2 = *localtime(&time2);

  cout << "time: " << asctime(&timeinfo1);// << endl;
  cout << "time: " << asctime(&timeinfo2);// << endl;

  return 0;
}