eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

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

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

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

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)