User7723337
User7723337

Reputation: 12018

How to convert epoch time to year

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.

Upvotes: 7

Views: 11320

Answers (3)

Fred Nurk
Fred Nurk

Reputation: 14212

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.

You don't need the year, month, day of either timestamp for this. Subtract the two epoch times to get a value in seconds. Divide by 60*60*24*365 to get a value in years:

int main() {
  time_t past = 1234567890;
  time_t now = time(0);
  double years = double(now - past) / 60 / 60 / 24 / 365;
  cout << "years = " << years << '\n';
  return 0;
}

This will be off by any leap seconds that have occurred between the two timestamps, but, significantly, it gives the correct value within a year. For example, 1 Dec. 2010 to 1 Jan. 2011 is approximately 1/12th of a year, not 1 year.

Upvotes: 3

Eli Iser
Eli Iser

Reputation: 2834

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;

Upvotes: 7

peoro
peoro

Reputation: 26060

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

Upvotes: 5

Related Questions