簡單好用的返回明天0點,昨天0點等任意天數的方法
快速入口:主要思路是在定日期格式時,直接定死時分秒
private static String timeInterval(int amount)throws Exception{
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
calendar.add(Calendar.DATE, amount);
String strTime = sdf.format(calendar.getTime());
return strTime;
}
(1)當需求要求一個日期格式的時間時,可用:
/**
* 計算距此時往前或往後天數0點時間
* @param amount 天數
* @return 返回Date類型的時間
* @throws Exception
*/
private static Date timeInterval(int amount)throws Exception{
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
calendar.add(Calendar.DATE, amount);
String strTime = sdf.format(calendar.getTime());
Date time = sdf.parse(strTime);
return time;
}
public static void main(String[] args) throws Exception {
String time = timeInterval(3);
System.out.println(time);
}
輸出結果:
輸入 2 -> 2020-05-06 00:00:00
輸入 5 -> 2020-05-09 00:00:00
輸入 -1 -> 2020-05-03 00:00:00
(2)普遍適用,滿足需求是返回字符串格式的時間:
/**
* 計算距此時往前或往後天數0點時間
* @param amount 天數
* @return 返回的String格式的時間
* @throws Exception
*/
private static String timeInterval(int amount)throws Exception{
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
calendar.add(Calendar.DATE, amount);
String strTime = sdf.format(calendar.getTime());
return strTime;
}
public static void main(String[] args) throws Exception {
String time = timeInterval(-1);
System.out.println(time);
}
輸出結果:
輸入 2 -> 2020-05-06 00:00:00
輸入 5 -> 2020-05-09 00:00:00
輸入 -1 -> 2020-05-03 00:00:00
注:可修改參數更改日期格式new SimpleDateFormat("yyyy-MM-dd 00:00:00")
如,new SimpleDateFormat("yyyy-MM-dd"),就會輸出 2020-05-06,看具體需求。