Great Falcon
Great Falcon

Reputation: 41

How to Convert Date String to OffsetDateTime

I have Date String and want to convert it into Java.util.OffSetDateTime

Tried below code but getting exception DateTimeParseException.

String ts="2020-06-01T13:46:45.641956";
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSS");
OffsetDateTime date = OffsetDateTime.parse(ts, fmt);
System.out.println(date);

Upvotes: 0

Views: 2215

Answers (1)

Basil Bourque
Basil Bourque

Reputation: 338775

tl;dr

Use the appropriate class. And, omit the formatter.

LocalDateTime.parse( "2020-06-01T13:46:45.641956" )

See this code run live at IdeOne.com.

Details

No need to specify a formatting pattern.

Your input happens to comply with the ISO 8601 standard. The java.time classes default to those standard formats when parsing or generating text.

But you are using the wrong class for your input. Your input lacks any indication of an offset-from-UTC. So you cannot parse as an OffsetDateTime. Instead, use LocalDateTime.

LocalDateTime ldt = LocalDateTime.parse( "2020-06-01T13:46:45.641956" ) ;

Upvotes: 2

Related Questions