Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting UTC time as time_t

Tags:

c

I am trying to get UTC time as time_t. Code below seems giving it correct but surprisingly prints local time only:

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 values of mytime and utctime we get are different. However, when passed as parameters to ctime it converts them to same string.

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

like image 827
Atul Avatar asked Aug 16 '15 17:08

Atul


3 Answers

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

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

like image 116
cup Avatar answered Oct 27 '22 07:10

cup


By definition the C time() function returns a time_t epoch time in UTC. So the code commented "//get the local time in time_t" is really getting UTC already, and the comment is incorrect.

From the Linux man-page:

time_t time(time_t *tloc);
time() returns the time as the number of seconds since the Epoch, 1970-01-01 00:00:00 +0000 (UTC).

Giving the code:

#include <time.h>

...

time_t utc_now = time( NULL );
like image 38
Kingsley Avatar answered Oct 27 '22 07:10

Kingsley


That's exactly what the documented behavior is supposed to do:

Interprets the value pointed by timer as a calendar time and converts it to 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 instead.

like image 24
Amit Avatar answered Oct 27 '22 06:10

Amit