How to Parse/Format Dates With Localdatetime - Java 8

How to parse/format dates with LocalDateTime? (Java 8)

Parsing date and time

To create a LocalDateTime object from a string you can use the static LocalDateTime.parse() method. It takes a string and a DateTimeFormatter as parameter. The DateTimeFormatter is used to specify the date/time pattern.

String str = "1986-04-08 12:30";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
LocalDateTime dateTime = LocalDateTime.parse(str, formatter);

Formatting date and time

To create a formatted string out a LocalDateTime object you can use the format() method.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
LocalDateTime dateTime = LocalDateTime.of(1986, Month.APRIL, 8, 12, 30);
String formattedDateTime = dateTime.format(formatter); // "1986-04-08 12:30"

Note that there are some commonly used date/time formats predefined as constants in DateTimeFormatter. For example: Using DateTimeFormatter.ISO_DATE_TIME to format the LocalDateTime instance from above would result in the string "1986-04-08T12:30:00".

The parse() and format() methods are available for all date/time related objects (e.g. LocalDate or ZonedDateTime)

Convert String to LocalDateTime Java 8

You don't need to specify a DateTimeFormatterin this case because the default one will be used if you don't pass one at all:

public static void main(String[] args) {
String dateStr = "2020-08-17T10:11:16.908732";
LocalDateTime dateTime = LocalDateTime.parse(dateStr);
System.out.println(dateTime);
}

That code will output 2020-08-17T10:11:16.908732.

If you are insisting on using a custom DateTimeFormatter, consider the T by single-quoting it in the pattern and don't use nanosecond parsing (n) for parsing fractions of second (S), the result might be wrong otherwise.

Do it like this:

public static void main(String[] args) {
String dateStr = "2020-08-17T10:11:16.908732";
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSS");
LocalDateTime dateTime = LocalDateTime.parse(dateStr, format);
System.out.println(dateTime);
}

with the same output as above.

Note:

The result of using the pattern "yyyy-MM-dd'T'HH:mm:ss.nnnnnn" would not be equal to the parsed String, instead, it would be

2020-08-17T10:11:16.000908732

Java 8 LocalDateTime

From the JAVA Oracle docs,

  • static LocalDateTime parse(CharSequence text)
    Obtains an instance of LocalDateTime from a text string such as 2007-12-03T10:15:30.

  • static LocalDateTime parse(CharSequence text, DateTimeFormatter formatter)
    Obtains an instance of LocalDateTime from a text string using a specific formatter.

DateTimeFormatter object needs to be formatted.

Java: Parse multiple String Date Time format into LocalDateTime/Date/Calender

tl;dr

LocalDateTime.parse(dateTimeString, DateTimeFormatter.ofPattern("M/d/yyyy h:m:s a");

is sufficient for all of your datetime examples.


The following example is able to parse all of your sample datetime Strings by using LocalDateTime.parse instead of DateTimeFormatter.parse, which are different:

public static void main(String[] args) {
String first = "12/21/2020 12:12:12 PM";
String second = "1/12/2020 2:6:8 PM";
String third = "10/2/2020 10:50:8 AM";

DateTimeFormatter dtf = DateTimeFormatter
.ofPattern("[MM/dd/yyyy HH:mm:ss a][M/dd/yyyy h:m:s a][MM/d/yyyy HH:mm:s a]");

System.out.println(LocalDateTime.parse(first, dtf));
System.out.println(LocalDateTime.parse(second, dtf));
System.out.println(LocalDateTime.parse(third, dtf));
}

Have a look at the second / middle pattern used, it uses h (lower case) for hours instead of an H (upper case) because the AM/PM of day will be derived from a capital H, too and that would lead to a conflict in the second datetime sample "1/12/2020 2:6:8 PM" where 02:06:08 is considered AM, but is followed by PM in the pattern.

The output of my solution is this:

2020-12-21T12:12:12
2020-01-12T14:06:08
2020-10-02T10:50:08

which correctly parses the time to PM (14 = 02 PM).

Note:

Don't use this DateTimeFormatter for output LocalDateTime.format(DateTimeFormatter) because it would return all three formattings defined...

Very ugly: 10/02/2020 10:50:08 AM10/02/2020 10:50:8 AM10/2/2020 10:50:8 AM

Converting String into LocalDateTime using Java 8 DateTimeFormatter

The format you want for output ("dd.MM.yyyy. HH:mm:ss") is not the same as the input, so you can't use it to parse.

In this specific case, the input is in ISO8601 format, so you can just parse it directly. Then you use the formatter to format the LocalDateTime object to the format you want:

String time1 = "2017-10-06T17:48:23.558";
// convert String to LocalDateTime
LocalDateTime localDateTime = LocalDateTime.parse(time1);
// parse it to a specified format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy. HH:mm:ss");
System.out.println(localDateTime.format(formatter));

The output is:

06.10.2017. 17:48:23


PS: If the input was in a different format, you should use one formatter to parse and another one to format. Check the javadoc to see all available formats.

Parse date or datetime both as LocalDateTime in Java 8

Just create custom formatter with the builder DateTimeFormatterBuilder

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("yyyy-MM-dd[ HH:mm:ss]")
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
.toFormatter();

This formatter uses the [] brackets to allow optional parts in the format, and adds the default values for hour HOUR_OF_DAY, minute MINUTE_OF_HOUR and second SECOND_OF_MINUTE.

note: you can ommit, minutes and seconds, just providing the hour is enough.

And use it as usual.

LocalDateTime localDateTime1 = LocalDateTime.parse("1994-05-13", formatter);
LocalDateTime localDateTime2 = LocalDateTime.parse("1994-05-13 23:00:00", formatter);

This outputs the correct date time with default hours of 0 (starting of the day).

System.out.println(localDateTime1); // 1994-05-13T00:00
System.out.println(localDateTime2); // 1994-05-13T23:00

Java 8 DateTimeFormatter parse fails for ISO dates far in future

Prepend +

  • Years with more than four digits are expected to have a leading PLUS SIGN character (+) for positive years (AD).
  • Negative years (BC) with any count of integers always lead with a MINUS SIGN (-).

The java.time classes generally follow the rules laid down in the ISO 8601 standard. See Wikipedia page on handling years in ISO 8601.

Code:

OffsetDateTime ldt = OffsetDateTime.parse( "+10000-04-11T01:24:55.887-03:56" ) ;

See this code run live at IdeOne.com.



Related Topics



Leave a reply



Submit