求前五分钟所在的分钟数为5的倍数的时间段

项目中的需要用到的一个小的时间条件,表数据是每五分钟统计一次,查询的时间条件就是当前时间前五分钟所在的分钟数为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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章