Gustavo Rozolin
Gustavo Rozolin

Reputation: 1117

How is a date value represented as a long integer translated into a meaningful date?

I want to know, how does this work? When I pass a long integer as a date, how is that value transformed into a Date?

Ex:

    public Date converter(Long time){
     //what the magic?
    }

This question is not new Date(long), I know this. But what do I want to know what calculations are used internally to produce the (human-meaningful) date value.

Upvotes: 0

Views: 592

Answers (1)

Hot Licks
Hot Licks

Reputation: 47739

Roughly speaking:

int days = longTimeInSeconds / (60 * 60 * 24);
int timeOfDay = longTimeInSeconds % (60 * 60 * 24);  // Leave converting this to hours/mins/secs to the student
int fourYearIntervals = days / (365 * 4 + 1);
int daysInInterval = days % (365 * 4 + 1);
int yearInInterval = daysInInterval / 365;
int daysInYear = daysInInterval % 365;  // For the student to convert to months/days
int year = fourYearIntervals * 4 + yearInInterval;

I think an additional fudge is required to account for the fact that 1970 was not a 4-year-interval boundary, but the above should be pretty close.

Key is understanding that every 4th year is a leap year, so the years are in 4-year intervals. (The rules say that every 100th year is NOT a leap year, meaning that 2000 would not be one, but then a further rule says that every 400th year IS a leap year, so we're "safe" between 1901 and 2099. Be thankful that you won't be around to see the disasters that occur due to the "Y2.1K bug".)

But keep in mind that many Time object classes store the time internally as a single number similar to the original long above, and only do the above conversions when asked to produce a character representation of the date, or to otherwise break it down into years/months/days.

Upvotes: 4

Related Questions