开发者

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.


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;


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜