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.
yyyy-MM-ddThh:mm:ss
1.1. Default Pattern -> 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 !!
Comments