How to convert era to year

I have time in era format.
I just want to extract Year from it.

how do we do this in c or c ++?

In fact, I have time since the era in seconds, and I need to calculate the age based on this. Thus, the input will be seconds, since the epoch and exit should be Age, based on the current date.

Thanks,
PP.

+5
source share
3 answers

C timestamps (i.e.: seconds from an era) are usually stored in time_t, and human dates are stored in a structure tm. You need a function that converts time_tto tms.

gmtime localtime - C, .

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

, . POSIX- (linux, mac os x,...): gmtime_r localtime_r

+3

gmtime localtime time_t struct tm. tm_year , .

-, .

Edit:

:

time_t nowEpoch = time(NULL);
struct tm* nowStruct = gmtime(&nowEpoch);
int year = nowStruct->tm_year + 1900;
+5

, . , , Age .

You do not need a year, month, day, or time stamp to do this. Subtract two time periods to get the value in seconds. Divide by 60 * 60 * 24 * 365 until you get the 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 disabled by any second seconds that occur between two timestamps, but, to a large extent, it gives the correct value for a year. For example, from December 1, 2010 to January 1, 2011, this is approximately 1/12 year, and not 1 year.

0
source

All Articles