項目中的需要用到的一個小的時間條件,表數據是每五分鐘統計一次,查詢的時間條件就是當前時間前五分鐘所在的分鐘數爲5的倍數倍的時間段,着急將就寫了一個,也沒有什麼好的思路
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
calendar.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE) - 5);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:00");
SimpleDateFormat hourDf = new SimpleDateFormat("mm");
String time=hourDf.format(calendar.getTime());
//分鐘數是5的多少倍
int n=Integer.valueOf(time)/5;
//五分鐘前時間所在的小時
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:00:00");
calendar.setTime(format.parse(format.format(calendar.getTime())));
calendar.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE)+5*n);
String time2=df.format(calendar.getTime());
calendar.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE)+5);
String time3=df.format(calendar.getTime());
System.out.println(time2);
System.out.println(time3);
} catch (ParseException e) {
e.printStackTrace();
}
}
測試結果1:
輸入時間:2020-06-05 15:01:00
前五分鐘開始時間點:2020-06-05 14:55:00
前五分鐘結束時間點:2020-06-05 15:00:00
測試結果2:
輸入時間:2020-06-05 15:49:00
前五分鐘開始時間點:2020-06-05 15:40:00
前五分鐘結束時間點:2020-06-05 15:45:00