1

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?

cHao
  • 82,321
  • 20
  • 145
  • 171

3 Answers3

15

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();
}
Jordi Castilla
  • 25,851
  • 7
  • 65
  • 105
Asif Mujteba
  • 4,548
  • 2
  • 21
  • 38
0
fun roundDate(date: Date): Date {
        val minToMs = TimeUnit.MINUTES.toMillis(60)
        val roundAdd = minToMs - date.time % minToMs
        return Date(date.time + roundAdd)
}
-1

Easy way to solve this issue:

var d = new Date();
d.setMinutes (d.getMinutes() + 60);
d.setMinutes (0);
Jordi Castilla
  • 25,851
  • 7
  • 65
  • 105
Srb
  • 199
  • 3
  • 13