Omkar Shetkar
Omkar Shetkar

Reputation: 3636

Epoch time to struct tm conversion in C

I have input time in seconds epoch format. I need to have struct tm out of this epoch time in seconds.

    struct tm epoch_time;
    int seconds = 1441852;
    epoch_time.tm_sec = seconds;

My purpose is to have tm structure filled with proper values for years, months, days, hours, minutes, and seconds for the given epoch time in seconds. Any hint in this regard will be helpful. Thanks.

Upvotes: 1

Views: 7837

Answers (1)

David Schwartz
David Schwartz

Reputation: 182883

struct tm epoch_time;
time_t seconds = 1441852;
memcpy(&epoch_time, localtime(&seconds), sizeof (struct tm));

This assumes you want local time. If you want GMT, use gmtime instead of localtime. Note that this will crash on error.

Upvotes: 4

Related Questions