Kevin Bowersox Kevin Bowersox - 2 months ago 19
Java Question

Java Milliseconds in Year

I am doing some date calculations in Java using milliseconds. I do not have much experience working with milliseconds and cannot even determine how many milliseconds are in a year. Here is my attempt:

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 = 31556952000 Milliseconds, so my multiplication is off somehow.

Can anyone point out what I am doing wrong? Should I be using a long?

Answer

Should I be using a long?

Yes. The problem is that, since MILLIS_IN_SECOND and so on are all ints, 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;
Comments