I want to round a Date
object to the next whole hour. For example, 04:15 should be converted to 05:00.
How can I do this?
I want to round a Date
object to the next whole hour. For example, 04:15 should be converted to 05:00.
How can I do this?
You can use use the Calendar
class to do this:
public Date roundToNextWholeHour(Date date) {
Calendar c = new GregorianCalendar();
c.setTime(date);
c.add(Calendar.HOUR, 1);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
return c.getTime();
}
fun roundDate(date: Date): Date {
val minToMs = TimeUnit.MINUTES.toMillis(60)
val roundAdd = minToMs - date.time % minToMs
return Date(date.time + roundAdd)
}
Easy way to solve this issue:
var d = new Date();
d.setMinutes (d.getMinutes() + 60);
d.setMinutes (0);