Since JDK 8, we can create a datetime formatter / parser pattern that can have optional sections. When parsing a datetime string that contains optional values, for example, a date without time part or a datetime without second part, we can create a parsing pattern wrapped within the []
symbols. The [
character is the optional section start symbol, and the ]
character is the optional section end symbol. The pattern inside this symbol will be considered as an optional value.
We can use the java.time.format.DateTimeFormatter
class to parse the string of datetime or format the datetime object, and use it with the new Java time API classes such as java.time.LocalDate
or java.time.LocalDateTime
to convert the string into respective LocalDate
or LocalDateTime
object as show in the code snippet below.
package org.kodejava.datetime;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class DateTimeParseOptionalParts {
public static final String OPT_TIME_PATTERN = "yyyy-MM-dd[ HH:mm[:ss]]";
public static final String OPT_SECOND_PATTERN = "yyyy-MM-dd HH:mm[:ss]";
public static void main(String[] args) {
DateTimeFormatter optTimeFormatter = DateTimeFormatter.ofPattern(OPT_TIME_PATTERN);
LocalDate date1 = LocalDate.parse("2023-08-28", optTimeFormatter);
LocalDate date2 = LocalDate.parse("2023-08-28 17:15", optTimeFormatter);
LocalDate date3 = LocalDate.parse("2023-08-28 17:15:30", optTimeFormatter);
System.out.println("date1 = " + date1);
System.out.println("date2 = " + date2);
System.out.println("date3 = " + date3);
DateTimeFormatter optSecondFormatter = DateTimeFormatter.ofPattern(OPT_SECOND_PATTERN);
LocalDateTime datetime1 = LocalDateTime.parse("2023-08-28 17:15", optSecondFormatter);
LocalDateTime datetime2 = LocalDateTime.parse("2023-08-28 17:15:30", optSecondFormatter);
System.out.println("datetime1 = " + datetime1);
System.out.println("datetime2 = " + datetime2);
}
}
Here are the outputs of the code snippet above:
date1 = 2023-08-28
date2 = 2023-08-28
date3 = 2023-08-28
datetime1 = 2023-08-28T17:15
datetime2 = 2023-08-28T17:15:30
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024