Java Data Type How to - Round java.util.Date in 30 minutes with Instant








Question

We would like to know how to round java.util.Date in 30 minutes with Instant.

Answer

import java.time.Instant;
import java.util.Date;
//from   ww w  . ja  va2  s  .  co  m
public class Main {

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

  public static Date roundTo30Minutes(final Date from) {
    long t = from.getTime();
    t = t - (t % (1000 * 60 * 30));
    t += (1000 * 60 * 30);
    return Date.from(Instant.ofEpochMilli(t));
  }
}

The code above generates the following result.