Add 1 Week to a Date, which way is preferred?

前端 未结 10 1699
迷失自我
迷失自我 2021-01-07 17:30

I am reviewing some code at work and came across an inconsistency in how the code handles adding 1 week to the current time and was wondering if there was any reason why one

10条回答
  •  迷失自我
    2021-01-07 17:58

    Be very careful about using method two which caught me out the other day. Consider

    private static long ONE_YEAR_AS_MILLISECONDS = 365*24*60*60*1000;
    

    This looks innocent enough, but in fact will not produce what is expected as the multiplication uses integers which, when multiplied by each the other integers, causes a numeric overflow and will yield an unexpected result. This is because the max int value in Java is 2,147,483,647 and yet there are 31,536,000,000 ms in a year. On my machine the above code produces 1,471,228,928 which is obviously not correct.

    Instead you need to do this:

    private static long ONE_YEAR_AS_MILLISECONDS = 365L*24L*60L*60L*1000L;
    

提交回复
热议问题