Question

I have strings of unixtime and I want to compare them by hours and minutes.

For example:

unixtime1 = "1327418725" unixtime2 = "1327511595"

time_t convertUnixToTime(const char* unixtime){

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

I use the function as such:

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;

and I get the output:

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

I can't figure out why I'm getting the same time and also I want to be able to difftime() after to see how many HOURS and MINUTES they are apart.

Any suggestions/insight?

Was it helpful?

Solution

localtime() retuns a pointer to an object that is integral to the library. You are storing this pointer twice in timeinfo1 and timeinfo2.

You need to copy the 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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top