I am trying to convert the value 2022-04-30 14:34:52.900426 00:00
an instance of LocalDateTime
. I have written the following code:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSS'Z'");
I am getting the following error
could not be parsed at index 26
What should my formatter string be?
CodePudding user response:
tl;dr
OffsetDateTime // Use `OffsetDateTime`, not `LocalDateTime`, to represent a date with time and offset.
.parse(
"2022-04-30 14:34:52.900426 00:00" // Almost in ISO 8601 format.
.replace( " " , "T" ) // Replace SPACE with T to comply with ISO 8691.
)
See this code run live at IdeOne.com.
Wrong class, use OffsetDateTime
, not LocalDateTime
LocalDateTime
is exactly the wing class to use in this case. That represents a date with time-of-day. But your input indicates a date with time-of-day and an offset-from-UTC. The 00:00
means an offset of zero hours-minutes-seconds from UTC.
So parse that input as a OffsetDateTime
object instead.
Rather than define a formatting pattern, I suggest merely replacing the SPACE in the middle with a T
to comply with the ISO 8601 standard used by default in the java.time classes when parsing/generating text.
String input = "2022-04-30 14:34:52.900426 00:00".replace( " " , "T" ) ;
OffsetDateTime odt = OffsetDateTime.parse( input ) ;
CodePudding user response:
It's not working because the UTC Time offsets hasn't been written properly. It should look like this with a custom DateTimeFormatter
:
//Custom DatTimeFormatter
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSSZZZZZ");
formatter.parse("2022-04-30 14:34:52.900426 00:00");
You could either use the predefined ISO_OFFSET_DATE_TIME
DatTimeFormatter
only by replacing the space between date and time with a capital T, as the standard requires.
//Predefined DateTimeFormatter
DateTimeFormatter.ISO_OFFSET_DATE_TIME.parse("2022-04-30T14:34:52.900426 00:00");
Besides, to answer your question under @Taco Jan Osinga's reply:
No, it is not correct to use " 00:00" to just match the datetime you're trying to parse. That custom DateTimeFormatter
you would build would only match datetime referring to your local TimeZone; thus it won't work with datetime from different areas.
CodePudding user response:
Have you tried "yyyy-MM-dd HH:mm:ss.SSSSSS 00:00"
?