目的:獲取當前時間前n天的日期 (示例就以30天爲例)
運行代碼:
返回的類型 java.sql.Date
long time = 30*86400000;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String format = simpleDateFormat.format(new Date(System.currentTimeMillis() - time));
System.out.println("獲取到三十天前的日期爲:"+java.sql.Date.valueOf(format));
粗看代碼是沒有問題,運行出來的時間竟然是:
今天是5月30日,三十天前是6月19日。。。
debug斷點。。。
int的取值範圍爲: -2^31——2^31-1,即-2147483648——2147483647
。。。
強轉啊。。數據類型
30天之前的時間是259.。。。而int的取值範圍是214.。。。。強轉成負數。。而用long類型的值就不會。。
記一個坑。。
附錄:
java計算當前時間指定天數之前的日期,指定時間日期指定天數之前的日期。。的工具類
//方法一
long time = (long)30*86400000;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String format1 = simpleDateFormat.format(new Date(System.currentTimeMillis() - time));
System.out.println("方法一:獲取到三十天前的日期爲:"+java.sql.Date.valueOf(format1));
//方法二
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String maxDateStr = "2018-01-01";
String minDateStr = "";
Calendar calc =Calendar.getInstance();
try {
calc.setTime(sdf.parse(maxDateStr));
calc.add(calc.DATE, -30);
Date minDate = calc.getTime();
minDateStr = sdf.format(minDate);
System.out.println("方法二獲取指定日期2018-01-01之前的30天的日期爲:"+minDateStr);
} catch (ParseException e1) {
e1.printStackTrace();
}
//方法三
Calendar now = Calendar.getInstance();
now.add(Calendar.DAY_OF_MONTH, -30);
String endDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(now.getTime());
System.out.println("方法三:獲取當前時間前30天的日期,時分秒:"+endDate);
//方法四
LocalDateTime now1 = LocalDateTime.now();
now1 = now1.minus(30, ChronoUnit.DAYS);
System.out.println("方法四:java8新特性獲取當前時間30天的日期"+now1.toString());
//方法五
Date now2 = new Date();
Date startDate = DateUtils.addDays(now2, -30);
System.out.println("方法五:lang3中的工具類DateUtils獲取當前日期30天的日期爲:"+startDate);
//方法六
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar c = Calendar.getInstance();
//過去七天
c.setTime(new Date());
c.add(Calendar.DATE, - 7);
Date d = c.getTime();
String day = format.format(d);
System.out.println("方法六,當前時間前七天:"+day);
//過去一月
c.setTime(new Date());
c.add(Calendar.MONTH, -1);
Date m = c.getTime();
String mon = format.format(m);
System.out.println("方法六,當前時間過去一個月:"+mon);
//過去三個月
c.setTime(new Date());
c.add(Calendar.MONTH, -3);
Date m3 = c.getTime();
String mon3 = format.format(m3);
System.out.println("方法六,當前時間過去三個月:"+mon3);
//過去一年
c.setTime(new Date());
c.add(Calendar.YEAR, -1);
Date y = c.getTime();
String year = format.format(y);
System.out.println("方法六,當前時間,過去一年:"+year);
每個都進行驗證了。。。媽媽再也不用擔心我的時間計算了。。。