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
  • 84,970
  • 20
  • 145
  • 172

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
  • 26,609
  • 8
  • 70
  • 109
Asif Mujteba
  • 4,596
  • 2
  • 22
  • 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
  • 26,609
  • 8
  • 70
  • 109
Srb
  • 219
  • 3
  • 13