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
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?
This is the number of seconds since the 1970 epoch. To convert seconds to milliseconds, you need to multiply the number of seconds by 1000. To convert a Date to milliseconds, you could just call timeIntervalSince1970 and multiply it by 1000 every time.
The millis() method of Clock class returns the current instant of the clock in milliseconds. A millisecond instant is measured from 1970-01-01T00:00Z (UTC) to the current time. This method does the same work as System. currentTimeMillis() method.
Actually java. util. Date is internally specified in milliseconds from epoch. So any date is the number of milliseconds passed since January 1, 1970, 00:00:00 GMT and Date provides constructor which can be used to create Date from milliseconds.
Should I be using a long?
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.
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;
If on android, I suggest:
android.text.format.DateUtils
DateUtils.SECOND_IN_MILLIS
DateUtils.MINUTE_IN_MILLIS
DateUtils.HOUR_IN_MILLIS
DateUtils.DAY_IN_MILLIS
DateUtils.WEEK_IN_MILLIS
DateUtils.YEAR_IN_MILLIS
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With