Round java.util.Date to end of day

4.3k Views Asked by At

I want to round a java.util.Date object to the end of the day, e.g. rounding 2016-04-21T10:28:18.109Z to 2016-04-22T00:00:00.000Z.

I saw Java Date rounding, but wasn't able to find something compareable for the end of the day. It also is not the same as how to create a Java Date object of midnight today and midnight tomorrow?, because I don't want to create a new Date (midnight today or tomorrow), but the next midnight based on any given date.

3

There are 3 best solutions below

2
On BEST ANSWER

The DateUtils.ceiling serves your purpose. Pass Calendar.DATE for field value.

0
On

Traditional way

@Test
public void testDateRound() throws ParseException {
    Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").parse("2016-04-21T10:28:18.109Z");
    System.out.println(date);
    Calendar cl = Calendar.getInstance();
    cl.setTime(date);
    cl.set(Calendar.HOUR_OF_DAY, 23);
    cl.set(Calendar.MINUTE, 59);
    cl.set(Calendar.SECOND, 59);
    cl.set(Calendar.MILLISECOND, 999);
    System.out.println(cl.getTime());
    cl.add(Calendar.MILLISECOND, 1);
    System.out.println(cl.getTime());
}

Output

Thu Apr 21 10:28:18 GMT+03:00 2016
Thu Apr 21 23:59:59 GMT+03:00 2016
Fri Apr 22 00:00:00 GMT+03:00 2016
0
On

Given the documentation of DateUtils, I'm not sure I'd trust it with this.

Assuming you're only interested in a UTC day, you can take advantage of the fact that the Unix epoch is on a date boundary:

public static Date roundUpUtcDate(Date date) {
    long millisPerDay = TimeUnit.DAYS.toMillis(1);
    long inputMillis = date.getTime();
    long daysRoundedUp = (inputMillis + (millisPerDay - 1)) / millisPerDay;
    return new Date(daysRoundedUp * millisPerDay);
}

I would strongly urge you to move to the java.time API if you possibly can though.