Java Milliseconds in Year

前端 未结 9 1907
终归单人心
终归单人心 2020-12-09 08:24

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;
             


        
9条回答
  •  天命终不由人
    2020-12-09 08:49

    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;
    

提交回复
热议问题