LocalDateTime parse()

Java 8 LocalDateTime class represents a date without associated timezone information. Learn to convert a date in string to LocalDateTime object in Java 8.

1. String to LocalDateTime example – default and custom patterns

Java example to convert a string into LocalDateTime using LocalDateTime.parse() method.

//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.

2019-03-27T10:15:30
2019-03-27T10:15:30

2. DateTimeFormatter.ISO_LOCAL_DATE_TIME

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. DateTimeFormatter with Locale

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.

2019-05-29T10:15:30

Drop me your questions related to string to localdatetime conversion in Java 8 – in comments.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.