年份中的Java毫秒数 [英] Java Milliseconds in Year
问题描述
我在Java中使用毫秒进行一些日期计算并注意到以下问题:
I am doing some date calculations in Java using milliseconds and noticing an issue with the following:
private static final int MILLIS_IN_SECOND = 1000;
private static final int SECONDS_IN_MINUTE = 60;
private static final int MINUTES_IN_HOUR = 60;
private static final int HOURS_IN_DAY = 24;
private static final int DAYS_IN_YEAR = 365; //I know this value is more like 365.24...
private static final long MILLISECONDS_IN_YEAR = MILLIS_IN_SECOND * SECONDS_IN_MINUTE * MINUTES_IN_HOUR * HOURS_IN_DAY * DAYS_IN_YEAR;
System.out.println(MILLISECONDS_IN_YEAR); //Returns 1471228928
我知道1年大致 = 31,556,952,000毫秒,所以我的乘法不知何故。
I know that that 1 Year is roughly = 31,556,952,000 Milliseconds, so my multiplication is off somehow.
任何人都可以指出我做错了什么?我应该使用多长时间?
Can anyone point out what I am doing wrong? Should I be using a long?
推荐答案
我应该使用多头吗?
Should I be using a long?
是的。问题是,因为 MILLIS_IN_SECOND
等等都是 int
s,当你乘以它们时你得到一个 INT
。您将 int
转换为 long
,但仅 <$ c后$ c> int 乘法已经导致错误答案。
Yes. The problem is that, since MILLIS_IN_SECOND
and so on are all int
s, when you multiply them you get an int
. You're converting that int
to a long
, but only after the int
multiplication has already resulted in the wrong answer.
要解决此问题,您可以将第一个转换为 long
:
To fix this, you can cast the first one to a long
:
private static final long MILLISECONDS_IN_YEAR =
(long)MILLIS_IN_SECOND * SECONDS_IN_MINUTE * MINUTES_IN_HOUR
* HOURS_IN_DAY * DAYS_IN_YEAR;
这篇关于年份中的Java毫秒数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!