简体   繁体   English

如何将以长整数表示的日期值转换为有意义的日期?

[英]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 ? 当我将整数作为日期传递时,该值如何转换为Date

Ex: 例如:

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

This question is not new Date(long), I know this. 这个问题不是新的Date(long),我知道这一点。 But what do I want to know what calculations are used internally to produce the (human-meaningful) date value. 但是我想知道内部使用什么计算来产生(有意义的)日期值。

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. 我认为需要额外增加一些预算,以说明1970年不是一个4年间隔的边界,但是上述情况应该非常接近。

Key is understanding that every 4th year is a leap year, so the years are in 4-year intervals. 关键是要了解每4年是year年,因此年份间隔为4年。 (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".) (规则说每100年不是a年,这意味着2000年不会是leap年,但是另一条规则则说每400年是a年,因此我们在1901年到2099年之间是“安全的”。感激您将不会看到因“ Y2.1K错误”而导致的灾难。)

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. 但请记住,许多时间对象类在内部将时间存储为一个单一的数字,类似于上面的原始long ,并且仅在要求生成日期的字符表示形式或以其他方式将其分解为年/时才进行上述转换。月/日。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM