java中long值表达式需要注意的一种情况

今天工作中遇到一个情况,


long bigInterval = 7 * 30 * 24 * 60 * 60 * 1000;
 
  
但是实际使用中发现计算出来的bigInterval值为 bigInterval:964130816
 
  
然后发现这个值是不对的,编译和运行不会报错,但是会有提示,Numeric overflow in expression
也就是说,右边算出来的是int类型,但是计算值超出了int的值范围,所以需要修改
 
  
改为:
 
  
long bigInterval = 7L * 30L * 24L * 60L * 60L * 1000L;
问题解决,计算出来的bigInterval值为: bigInterval:18144000000
 
  
测试代码:
 
  
private static void testTimeInterval() throws Exception {
    String time1 = "2016-04-06 14:11:14";
    String time2 = "2016-04-18 00:00:00";

    long bigInterval = 7L * 30L * 24L * 60L * 60L * 1000L;

    System.out.println("bigInterval:" + bigInterval);

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    long longTime1 = sdf.parse(time1).getTime();
    long longTime2 = sdf.parse(time2).getTime();

    System.out.println("longTime1:" + longTime1);
    System.out.println("longTime2:" + longTime2);

    long inervalTime3 = longTime2 - bigInterval;
    System.out.println("intervalTime3:" + inervalTime3);

    System.out.println(longTime1 - inervalTime3);
}



你可能感兴趣的:(java后端)