Atul
Atul

Reputation: 4340

Getting UTC time as time_t

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)

Upvotes: 10

Views: 27486

Answers (4)

Kingsley
Kingsley

Reputation: 14916

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 );

Upvotes: 6

cup
cup

Reputation: 8267

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.

Upvotes: 5

ameyCU
ameyCU

Reputation: 16607

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

To get 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 function GetSystemTime in for windows.

Upvotes: 2

Amit
Amit

Reputation: 46341

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.

Upvotes: 2

Related Questions