Convert String to LocalDateTime

Java LocalDateTime class represents an instant in local timeline i.e. without any timezone information. Learn to convert string to LocalDateTime object in Java.

1. Parse String to LocalDateTime

The LocalDateTime.parse() method takes two arguments. The first argument is the string representing the date. And the second optional argument is an instance of DateTimeFormatter specifying any custom pattern.

//Default pattern

LocalDateTime today = LocalDateTime.parse("2019-03-27T10:15:30");
System.out.println(today);

//Custom pattern

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss a");
LocalDateTime dateTime = LocalDateTime.parse("2019-03-27 10:15:30 AM", formatter);
System.out.println(dateTime);

Program output.

2021-03-27T10:15:30
2021-03-27T10:15:30

2. Default Pattern

The default date pattern is DateTimeFormatter.ISO_LOCAL_DATE_TIME which is yyyy-MM-ddThh:mm:ss.

The format consists of:

  • The ISO_LOCAL_DATE
  • The letter ‘T’. Parsing is case insensitive.
  • The ISO_LOCAL_TIME

ISO_LOCAL_DATE_TIME = ISO_LOCAL_DATE + ‘T’ + ISO_LOCAL_TIME

3. Locale Specific date Patterns

Sometimes we may have dates in specific locales such as french e.g. 29-Mar-2019 will be written in French as 29-Mars-2019. To parse such dates, use DateTimeFormatter withLocale() method to get the formatter in that locale and parse the dates.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MMMM-dd HH:mm:ss a")
                                        .withLocale(Locale.FRENCH);

LocalDateTime date = LocalDateTime.parse("2019-mai-29 10:15:30 AM", formatter);

System.out.println(date);

Program output.

2021-05-29T10:15:30

Happy Learning !!

Sourcecode on Github

Leave a Reply

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.

Our Blogs

REST API Tutorial