Convert String to LocalDateTime in Java

Convert String to LocalDateTime in Java

In this article, we will see how to convert String to LocalDateTime in Java.

LocalDateTime class was introduced in Java 8. LocalDateTime represents local date and time without timezone information. It is represented in ISO 8601 format (yyyy-MM-ddTHH:mm:ss) by default.

Java String to LocalDateTime

To convert String to LocalDateTime in Java, LocalDateTime provides static method parse() which takes String as input and returns LocalDateTime object.

parse() method accepts a date time String in ISO-8601 by default.

Output:

LocalDateTime obj: 2022-02-16T10:22:15

In case, if you provide String in any other format, it will throw DateTimeParseException.

Output:

Exception in thread “main” java.time.format.DateTimeParseException: Text ‘2022-02-16 10:22:15’ could not be parsed at index 10
at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2046)
at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1948)
at java.base/java.time.LocalDateTime.parse(LocalDateTime.java:492)
at java.base/java.time.LocalDateTime.parse(LocalDateTime.java:477)
at org.arpit.java2blog.StringToLocalDateTime.main(StringToLocalDateTime.java:13)

Convert String to LocalDateTime with custom format

To convert String to LocalDateTime with custom format, we can use DateTimeFormatter.

  • Create DateTimeFormatter instance with specified format
  • Pass date formatted String and DateTimeFormatter instance to LocalDateTime’s parse() method.

Output:

LocalDateTime obj: 2022-02-16T10:22

That’s all about how to convert String to LocalDateTime in Java.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *