Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 3522

Get Date and Time From a Datetime String in Java

$
0
0

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.

As always, the sample code used in this article is available over on GitHub.

       

Viewing all articles
Browse latest Browse all 3522

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>