Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 DateTimeFormatter to ignore millisecond and zone

I am struggling with Java 8 DateTimeFormatter.

I would like to convert a given String to dateFormat and parse to LocalDateTime

Here is my code

DateTimeFormatter f = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss")
String text = "2020-01-01T01:01:11.123Z"
LocalDateTime date = LocalDateTime.parse(text, f)

But Java throws

Text could not be parsed, unparsed text found at index 19

If I change ofPattern to yyyy-MM-dd'T'HH:mm:ss.SSSX, my code executes without any error. But I don’t want to use millisecond and time zone.

like image 356
J. Doem Avatar asked Feb 16 '18 00:02

J. Doem


People also ask

What can I use instead of SimpleDateFormat?

DateTimeFormatter is a replacement for the old SimpleDateFormat that is thread-safe and provides additional functionality.

What is DateTimeFormatter Iso_date_time?

static DateTimeFormatter. ISO_DATE_TIME. The ISO-like date-time formatter that formats or parses a date-time with the offset and zone if available, such as '2011-12-03T10:15:30', '2011-12-03T10:15:30+01:00' or '2011-12-03T10:15:30+01:00[Europe/Paris]'.

Is Java time format DateTimeFormatter thread-safe?

DateTimeFormatter is a formatter that is used to print and parse date-time objects. It has been introduced in Java 8. DateTimeFormatter is immutable and thread-safe.


1 Answers

Do this instead:

String text = "2020-01-01T01:01:11.123Z";
LocalDateTime date = ZonedDateTime.parse(text)
                                  .toLocalDateTime();

To get rid of the milliseconds information, do:

LocalDateTime date = ZonedDateTime.parse(text)
                                  .truncatedTo(ChronoUnit.SECONDS)
                                  .toLocalDateTime();

You can also use OffsetDateTime in place of ZonedDateTime.

like image 88
smac89 Avatar answered Sep 25 '22 15:09

smac89