How to round time to the nearest quarter hour in java?

后端 未结 14 2733
小鲜肉
小鲜肉 2020-11-27 14:59

Given today\'s time e.g. 2:24PM, how do I get it to round to 2:30PM?

Similarly if the time was 2:17PM, how do I get it to round to 2:15PM?

14条回答
  •  情书的邮戳
    2020-11-27 15:27

    Wonderful post, thank you so much guys! It was exactly what I needed :)

    Here's my code based on jour work.

    My usecase is "Given it's 11:47 am, I want to set two dates symbolizing the current 5-minutes frame : 11:45 am and 11:50 am"

                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.SECOND, 0);
                calendar.set(Calendar.MILLISECOND, 0);
    
                int modulo = calendar.get(Calendar.MINUTE) % 5;
                if(modulo > 0) {
    
                    calendar.add(Calendar.MINUTE, -modulo);
                }
    
                myObject.setStartDate(calendar.getTime());
    
                calendar.add(Calendar.MINUTE, 5);
                myObject.setDueDate(calendar.getTime()); 
    

提交回复
热议问题