Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert epoch time to year

Tags:

c++

c

I have time in epoch format.
I just want to retrieve Year from it.

how should we do it in c or c++ ?

Actually i have time since epoch in seconds and i need to calculate age depending on it.
So input will be seconds since epoch and out put should be Age based on current date.

Thanks,
PP.

like image 562
User7723337 Avatar asked Jan 31 '11 09:01

User7723337


2 Answers

Using the gmtime or localtime functions to convert the time_t to a struct tm. Then you can use the tm_year field of the struct to get the year.

Or for offline use, you can use a web converter, like this.

Edit:

Sample code:

time_t nowEpoch = time(NULL);
struct tm* nowStruct = gmtime(&nowEpoch);
int year = nowStruct->tm_year + 1900;
like image 88
Eli Iser Avatar answered Nov 01 '22 21:11

Eli Iser


In C timestamps (ie: seconds from epoch) are usually stored in time_t, while human-wise dates are stored in structure tm. You need a function that converts time_ts in tms.

gmtime or localtime are two C standard function that do your job.

struct tm *date = gmtime( your_time );
printf( "Year = %d\n", date->tm_year );

Warning that these functions are not thread-safe. You'll find a reentrant version on POSIX systems (linux, mac os x, ...): gmtime_r and localtime_r

like image 39
peoro Avatar answered Nov 01 '22 22:11

peoro