/***
* 获取计算日期source + days
* @param source 原日期。如:2019-04-09
* @param days 天数 -1
* @return 2019-04-08
*/
public static String getDate(String source, Integer days){
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date sourceDate,distDate;
try {
if(StrKit.isBlank(source)){
sourceDate = new Date();
}else{
sourceDate = new Date(sdf.parse(source).getTime());
}
distDate = new Date(sourceDate.getTime() + days * 24 * 60 * 60 * 1000 );
return sdf.format(distDate);
} catch (ParseException e) {
e.printStackTrace();
}
return "";
}如上代码,当days值太大或者太小,可能导致计算结果日期与预期值不一样。
原因:当days 取值范围是[-24,24]时,结果与预期一致,大于24或者小于-24时,days * 24 * 60 * 60 * 1000 超出了int的范围。
解决办法:将计算表表达式转换为long类型
distDate = new Date(sourceDate.getTime() + days * 24L * 60 * 60 * 1000 );版权声明:本文为xiaozaq原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。