Getting UTC time as time_t

I am trying to get UTC time as time_t . The code below seems correct, but surprisingly prints only local time:

 time_t mytime; struct tm * ptm; time ( &mytime ); // Get local time in time_t ptm = gmtime ( &mytime ); // Find out UTC time time_t utctime = mktime(ptm); // Get UTC time as time_t printf("\nLocal time %X (%s) and UTC Time %X (%s)", mytime, ctime(&mytime), utctime, ctime(&utctime)); 

As we can see the values โ€‹โ€‹of mytime and utctime , we get different. However, when passing ctime parameters ctime it converts them to one line.

Local time is 55D0CB59 (Sun Aug. 16 23:11:45 2015) and UTC 55D07E01 (Sun Aug. 16 23:11:45 2015)

+4
source share
3 answers

The result of ctime is a static variable. Do not use ctime twice in the same print statement. Do this in two separate print statements. A.

If ctime is replaced with asctime, the same problem occurs because asctime also returns the result as a static variable.

+3
source

Exactly what documented should do:

Interprets the value indicated by the timer as calendar time, and converts it into a C-string containing a human-readable version of the corresponding time and date, in terms of local time .

You probably want to use asctime .

+2
source
Function

ctime returns a string C containing date and time information in a human-readable format.

To get the time in UTC, you can use gettimeofday() (for Linux) -

  struct timeval ptm; gettimeofday(&ptm,NULL); long int ms = ptm.tv_sec * 1000 + ptm.tv_usec / 1000; 

And you can see the GetSystemTime function for windows.

+2
source

All Articles