Round java.util.Date to end of day

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.

Jon Skeet
people
quotationmark

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.

people

See more on this question at Stackoverflow