Convert String to LocalDateTime in Java

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.

1.1. Default Pattern -> yyyy-MM-ddThh:mm:ss

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

The format consists of the following:

  • 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

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

The program output:

2021-03-27T10:15:30

1.2. Custom Patterns

The custom patterns can be built using the DateTimeFormatter. Then pass its instance as the second argument to the LocalDateTime.parse() method.

final 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

2. Locale-specific 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

Comments

Subscribe
Notify of
guest
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.