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

Working with date and time is a common task in many Java applications. Whether for parsing input, formatting output, or manipulating dates and times within the program, Java provides robust tools to handle these tasks efficiently. Often, we receive a datetime string that needs manipulation, such as extracting the date and time separately for further processing.

In this article, we’ll look at various ways to extract the date and time separately from the input string.

2. Understanding the Problem

The most crucial step when working with datetime strings is deciding on a particular format. Without a standard format, correctly handling input strings becomes nearly impossible. Therefore, the format needs to be agreed upon beforehand.

For this tutorial, we’ll define a sample datetime string:

String datetime = "2024-07-04 11:15:24"

We’ll use the format yyyy-MM-dd HH:mm:ss as the expected standard. Additionally, we’ll support handling milliseconds with the format yyyy-MM-dd HH:mm:ss.SSS.

Given this input string, we should separate it into two strings: 2024-07-04 and 11:15:24.

3. Using split()

We can split the input string by space and separate the date and time part. Let’s look at the implementation:

@Test
void givenDateTimeString_whenUsingSplit_thenGetDateAndTimeParts() {
    String dateTimeStr = "2024-07-04 11:15:24";
    String[] split = dateTimeStr.split("\\s");
    assertEquals(2, split.length);
    assertEquals("2024-07-04", split[0]);
    assertEquals("11:15:24", split[1]);
}

This splits the string into date and time components. However, it’s important to note that this code will split even invalid strings without indicating any errors about the validity of the datetime string. Consequently, there might be more elegant solutions.

On the other hand, this approach can still split any input string if the date and time are separated by a space, making it applicable to many formats without specifying the exact pattern.

Let’s look at another example:

String dateTimeStr = "2024/07/04 11:15:24.233";
String[] split = dateTimeStr.split("\\s");
assertEquals(2, split.length);
assertEquals("2024/07/04", split[0]);
assertEquals("11:15:24.233", split[1]);

In the above example, the datetime doesn’t follow the expected pattern. However, we can still use this method since a space character separates the date and time parts.

However, if there is more than one space character in the string, then the splitting goes wrong. In such case we can use split() with limit parameter:

String dateTimeStr = "8/29/2011 11:16:12 AM";
String[] split = dateTimeStr.split("\\s", 2);
assertEquals(2, split.length);
assertEquals("8/29/2011", split[0]);
assertEquals("11:16:12 AM", split[1]);

Here, we use the split() function with a limit 2. This ensures the string is split at the first occurrence of the space character, with the remaining part returned as the second part. This method allows us to extract the date and time separately, even when additional markers such as AM/PM are present in the datetime string.

4. Using DateTimeFormatter

Another way to split the date and time component is by using the java.time APIs. We can parse the string into a LocalDateTime object using the DateTimeFormatter. After that, we can use the methods on the LocalDateTime object to separate the date and time components.

Let’s look at an example:

String dateTimeStr = "2024-07-04 11:15:24";
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);
DateTimeFormatter timeFormat = DateTimeFormatter.ofPattern("HH:mm:ss", Locale.ENGLISH);
LocalDateTime dateTime = LocalDateTime.parse(dateTimeStr, format);
assertEquals("2024-07-04", dateTime.toLocalDate().format(dateFormat));
assertEquals("11:15:24", dateTime.toLocalTime().format(timeFormat));

In this case, we created an instance of the DateTimeFormatter with the expected pattern for the input string. We can then parse the string into LocalDateTime using the formatter. After that, we can use its methods to retrieve the date and time components.

The advantage of this method over the split() function is that it allows us to validate whether the datetime string is valid. However, the downside is that we need to know the exact pattern beforehand, whereas the split() approach can handle multiple formats without knowing the exact format beforehand.

Let’s explore improving this implementation to support multiple formats while validating the datetime. We can use the DateTimeFormatterBuilder to define multiple formats. Here is an example:

DateTimeFormatter format1 = DateTimeFormatter.ofPattern("dd-MM-yyyy'T'HH:mm:ss.SSS", Locale.ENGLISH);
DateTimeFormatter format2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
DateTimeFormatterBuilder dateTimeFormatterBuilder = new DateTimeFormatterBuilder();
DateTimeFormatter multiFormatter = dateTimeFormatterBuilder
  .appendOptional(format1)
  .appendOptional(format2)
  .toFormatter(Locale.ENGLISH);

// case 1
LocalDateTime dateTime1 = LocalDateTime.parse("2024-07-04 11:15:24", multiFormatter);
String date1 = dateTime1.toLocalDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
String time1 = dateTime1.toLocalTime().format(DateTimeFormatter.ofPattern("HH:mm:ss"));
assertEquals("2024-07-04", date1);
assertEquals("11:15:24", time1);

// case 2
LocalDateTime dateTime2 = LocalDateTime.parse("04-07-2024T11:15:24.123", multiFormatter);
String date2 = dateTime2.toLocalDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
String time2 = dateTime2.toLocalTime().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"));
assertEquals("2024-07-04", date2);
assertEquals("11:15:24.123", time2);

In the above code sample, we utilized DateTimeFormatterBuilder to define multiple supported formats using the appendOptional() method. We then obtained a DateTimeFormatter instance by invoking the toFormatter() method. Consequently, we used this formatter to parse the input string. This approach allows us to parse three different formats easily.

However, the downside is that we must explicitly provide the exact format when converting back to separate date and time strings.

5. Using Regular Expressions

We can also use regular expressions to extract the date and time components separately. Let’s look at the usage of regular expression with a sample code:

String dateTimeStr = "2024-07-04 11:15:24.123";
Pattern pattern = Pattern.compile("(\\d{4}-\\d{2}-\\d{2})\\s(\\d{2}:\\d{2}:\\d{2}(\\.\\d{3})?)");
Matcher matcher = pattern.matcher(dateTimeStr);
assertTrue(matcher.matches());
assertEquals("2024-07-04", matcher.group(1));
assertEquals("11:15:24.123", matcher.group(2));

In this case, we use the regular expression to match and extract the date and time components from the string. This approach provides flexibility in handling various formats but requires careful regular expression crafting.

6. Conclusion

In this article, we explored various methods to separate date and time components from a datetime string in Java. We covered simple string splitting, using DateTimeFormatter, and employing DateTimeFormatterBuilder for multiple formats. Additionally, we discussed the use of regular expressions. Each method has pros and cons, and the choice depends on our application’s requirements and constraints.

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)