Java Data Type How to - Round date to hour








Question

We would like to know how to round date to hour.

Answer

import java.util.Calendar;
import java.util.Date;
/*from w  ww .  j  a v a 2  s .  com*/
public class Main {

  public static void main(String[] args) {
    System.out.println(round2Hour(new Date()));
  }

  public static Date round2Hour(Date date) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    return cal.getTime();
  }
}

The code above generates the following result.