Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Introduction

In some cases, while we’re working with dates in Java, we may have to round them to a certain unit, like hours, days, or months. It provides such benefits as aggregating data for analysis and reporting purposes and allowing to specify the degree of detail of displayed information.

In this tutorial, we’ll learn how to round the date using the java.util.Date, as well as LocalDateTime and ZonedDateTime.

2. Basic Rounding

In the basic rounding approach, we can truncate the time part of any date within Java. To be specific, this entails making all temporal elements equal to zero. Here’s how we can do that:

Date roundToDay(Date date) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    return calendar.getTime();
}

The roundToDay() method takes a Date object as a parameter. Then, we use the setTime() method from the Calender class and use it to use the set() method to round the hour, minute, second, and millisecond to the start of the day.

3. Rounding to the Nearest Unit

Wе havе thе option to makе thе rounding mеthod constant to makе thе datе match thе rounding across thе units such as hour, day, or month as follows:

Date roundToNearestUnit(Date date, int unit) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);

    switch (unit) {
        case Calendar.HOUR:
            int minute = calendar.get(Calendar.MINUTE);
            if (minute >= 0 && minute < 15) {
                calendar.set(Calendar.MINUTE, 0);
            } else if (minute >= 15 && minute < 45) {
                calendar.set(Calendar.MINUTE, 30);
            } else {
                calendar.set(Calendar.MINUTE, 0);
                calendar.add(Calendar.HOUR_OF_DAY, 1);
            }
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            break;

        case Calendar.DAY_OF_MONTH:
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            if (hour >= 12) {
                calendar.add(Calendar.DAY_OF_MONTH, 1);
            }
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            break;

        case Calendar.MONTH:
            int day = calendar.get(Calendar.DAY_OF_MONTH);
            if (day >= 15) {
                calendar.add(Calendar.MONTH, 1);
            }
            calendar.set(Calendar.DAY_OF_MONTH, 1);
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            break;
    }

    return calendar.getTime();
}

Here, we have a roundToNearestUnit() method that expects a Date and an int unit to be passed in, which seeks to round off the input date to the indicated time unit.

To that effect, the code creates an instance of Calendar and sets it to the input date. We’ll retrieve and adjust the minute, hour, or day component to allow a date to be rounded to the nearest 30-minute interval, day, or month depending upon which unit has been selected (Calendar.HOUR, Calendar.DAY_OF_MONTH, or Calendar.MONTH).

Moreover, we make sure the seconds and milliseconds are also zeroed. Following the above-mentioned modifications according to the defined time unit, the code returns the new Date derived from the generated Calendar entity.

4. Rounding Using LocalDateTime

LocalDateTime is a new class in Java that enables us to round dates at different levels, thereby offering a more current solution for handling dates and times. Here are two methods for rounding dates using LocalDateTime:

LocalDateTime roundToStartOfMonth(LocalDateTime dateTime) {
    return dateTime.withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
}

In the above method roundToStartOfMonth(), we set the day of the month to 1 to round the given LocalDateTime to the start of the month and reset all time components at midnight (0 hours, 0 minutes, 0 seconds, and 0 nanoseconds).

We can also use LocalDateTime to round the given date to the end of the week as follows:

LocalDateTime roundToEndOfWeek(LocalDateTime dateTime) {
    return dateTime.with(TemporalAdjusters.next(DayOfWeek.SATURDAY))
      .withHour(23)
      .withMinute(59)
      .withSecond(59)
      .withNano(999);
}

The RoundToEndOfWeek() method rounds LocalDateTime to the end of the next Saturday by taking advantage of TemporalAdjusters.next() function that finds the next Saturday and sets its time components such as 23 hours, 59 minutes, 59 seconds, and 999 nanoseconds.

5. Rounding Using ZonedDateTime

The ZonedDateTime class makes it possible to round dates for situations where there are time zones. Here are two methods for rounding dates using ZonedDateTime:

ZonedDateTime roundToStartOfMonth(ZonedDateTime dateTime) {
    return dateTime.withDayOfMonth(1)
      .withHour(0)
      .withMinute(0)
      .withSecond(0)
      .with(ChronoField.MILLI_OF_SECOND, 0)
      .with(ChronoField.MICRO_OF_SECOND, 0)
      .with(ChronoField.NANO_OF_SECOND, 0);
}

The above method roundToStartOfMonth() takes a ZonedDateTime as input and returns a new ZonedDateTime. Specifically, it returns the same date and time but with the time portion set to midnight at the beginning of the month (00:00:00.000).

To round the input Date to the end of the current week, let’s take the following example:

public static ZonedDateTime roundToEndOfWeek(ZonedDateTime dateTime) {
    return dateTime.with(TemporalAdjusters.next(DayOfWeek.SATURDAY))
      .withHour(23)
      .withMinute(59)
      .withSecond(59)
      .with(ChronoField.MILLI_OF_SECOND, 999)
      .with(ChronoField.MICRO_OF_SECOND, 999)
      .with(ChronoField.NANO_OF_SECOND, 999);
}

In the roundToEndOfWeek() method, we first find the next Saturday using TemporalAdjusters, then set the time to (23:59:59.999999999).

6. Conclusion

In conclusion, working with time-based data rounding dates in Java is one of the most important tasks. In this tutorial, we’ve seen some ways of rounding dates to different units and precision levels, such as truncating and the customized rounding method.

Be reminded that time changes should be put into consideration for every date, especially those for applications used internationally.

As always, the complete code samples for this article can be found over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.