user6039980
user6039980

Reputation: 3506

unix timestamp: not getting the correct year value by dividing

I'm attempting to extract years from the timestamp, as indicated below:

const int timestamp = 1499477613;
int hours = timestamp/3600;
int days = hours/24;
int years = days/356;
printf("years=%i\n", years);

However after executing the program, I get an output saying:

years=48

Which is different from the expected value 2017.

What's wrong with the code?

Upvotes: 1

Views: 146

Answers (1)

rafasc
rafasc

Reputation: 106

https://en.wikipedia.org/wiki/Unix_time

Unix time (also known as POSIX time or epoch time) is a system for describing instants in time, defined as the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970.

That result tells you that (approximately) 48 years has passed since that time. 1970 + 48 = 2018.

The reason you don't get an accurate value is precision you lose in each calculation. You're using ints to encode something that may return a floating point. (And what I assume to be a typo: days/356 should be days/365)

Upvotes: 1

Related Questions