Java Milliseconds in Year

前端 未结 9 1880
终归单人心
终归单人心 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 09:03

    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
    
    0 讨论(0)
  • 2020-12-09 09:03

    You're overflowing the int type. In Java, the result of a primitive arithmethic operation over two ints is an int. The type of the operands decides this, not the type of the result variable. Try:

    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 = (long) MILLIS_IN_SECOND * SECONDS_IN_MINUTE * MINUTES_IN_HOUR * HOURS_IN_DAY * DAYS_IN_YEAR;
    
    0 讨论(0)
  • 2020-12-09 09:06

    To fix this, you can put the letter L after the first one: e.g. 1000L

    long MILLS_IN_YEAR = 1000L * 60 * 60 * 24 * 365; // Returns 31536000000
    
    0 讨论(0)
提交回复
热议问题