Java 如何将日期值表示为长整数转换为有意义的日期?
我想知道,这是怎么回事?当我将一个长的整数作为日期传递时,该值如何转换为日期 例: 这个问题不是新的日期(很长),我知道这一点。但我想知道的是,内部使用了哪些计算来生成(有人类意义的)日期值。粗略地说:Java 如何将日期值表示为长整数转换为有意义的日期?,java,Java,我想知道,这是怎么回事?当我将一个长的整数作为日期传递时,该值如何转换为日期 例: 这个问题不是新的日期(很长),我知道这一点。但我想知道的是,内部使用了哪些计算来生成(有人类意义的)日期值。粗略地说: int days = longTimeInSeconds / (60 * 60 * 24); int timeOfDay = longTimeInSeconds % (60 * 60 * 24); // Leave converting this to hours/mins/secs to t
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;
我认为,1970年并不是一个4年间隔的边界,这一事实还需要一个额外的推敲,但上述情况应该非常接近
关键是要理解每四年都是闰年,所以每四年间隔一次。(规则说每100年不是闰年,也就是说2000年不是闰年,但另一条规则说每400年是闰年,所以我们在1901年到2099年之间是“安全的”。感谢你不会在这里看到因“Y2.1K错误”而发生的灾难。)
但请记住,许多时间对象类在内部将时间存储为单个数字,类似于上面原始的long
,并且仅在要求生成日期的字符表示形式或以其他方式将其分解为年/月/日时才进行上述转换。粗略地说:
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;
我认为,1970年并不是一个4年间隔的边界,这一事实还需要一个额外的推敲,但上述情况应该非常接近
关键是要理解每四年都是闰年,所以每四年间隔一次。(规则说每100年不是闰年,也就是说2000年不是闰年,但另一条规则说每400年是闰年,所以我们在1901年到2099年之间是“安全的”。感谢你不会在这里看到因“Y2.1K错误”而发生的灾难。)
但请记住,许多时间对象类在内部将时间存储为单个数字,类似于上面原始的
long
,并且仅在要求生成日期的字符表示形式或将其分解为年/月/天时才进行上述转换。返回新日期(时间)
但在使用Long
时,不要使用Long
时间,通常Long
时间从UTC 1970年1月1日起为秒或毫秒。把它转换成日期是一个简单的算术问题。他想知道它是如何工作的。比如它是如何把一个很长的时间变成一个日期的。你考虑过看源代码吗?@Garis M Suero,Reimeus这个问题与这个返回新日期(时间)
不同,但是当你使用long
时,不要花费long
时间,通常从1970年1月1日起,long
时间是秒或毫秒,UTC。把它转换成日期是一个简单的算术问题。他想知道它是如何工作的。就像它如何把一段很长的时间变成一次约会。你考虑过看源代码吗?@Garis M Suero,Reimeus这个问题与这个问题不同