java 获取若干小时之前的时刻 注意数据类型的范围问题

本文通过一个Java示例介绍了如何使用SimpleDateFormat进行日期格式化,并演示了如何通过减去特定毫秒数来计算过去的时间点。同时,文章还讨论了在进行长时间间隔运算时遇到的数据类型溢出问题及其解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

String tempStr = "";
  SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  Date dtNow = new Date();
  System.out.println("现在时刻:" + df.format(dtNow));
  long dlong = dtNow.getTime() - 1000 * 60 * 60 * 24 * 360;
  dtNow.setTime(dlong);
  tempStr = df.format(dtNow);
  System.out.println("之后时刻:" +tempStr);

运行结果:

现在时刻:2013-01-23 09:34:51
之后时刻:2013-01-11 08:54:22

 

如果是以上代码,那么1000 * 60 * 60 * 24 * 360就为int类型的,其最大取值为:System.out.println(Integer.MAX_VALUE);    结果:2147483647

而System.out.println(1000 * 60 * 60 * 24 * 360); 实际值是:1039228928,因为已超出范围,所以结果是这个了。

而System.out.println(1000 * 60 * 60 * 24 * 360L); 实际值是:31104000000,可以看出已经超出了,其最大值,所以最后结果是错误的。

 

改成一下代码:

String tempStr = "";
  SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  Date dtNow = new Date();
  System.out.println("现在时刻:" + df.format(dtNow));
  long dlong = dtNow.getTime() - 1000 * 60 * 60 * 24 * 360L;
  dtNow.setTime(dlong);
  tempStr = df.format(dtNow);
  System.out.println("之后时刻:" +tempStr);

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值