I'm trying to parse a datetime string in the following format:
2019-02-22 19:29:43+00:00
I'm following this guide: https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
This particular row seems to be the timestamp string that I'm trying to parse for:
Z zone-offset offset-Z +0000; -0800; -08:00;
Here is what I created, given that guide:
String input = "2019-02-22 19:29:43+00:00";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssX");
LocalDateTime parsed = LocalDateTime.parse(input, formatter);
But I get this error:
java.time.format.DateTimeParseException: Text '2019-02-22 19:29:43+00:00' could not be parsed, unparsed text found at index 22
• Wrong class: OffsetDateTime, not LocalDateTime.
• Replace SPACE with T for standard format used by default.
OffsetDateTime.parse( // Do NOT use `LocalDateTime` class, use `OffsetDateTime` because your input has an offset-from-UTC.
"2019-02-22 19:29:43+00:00"
.replace( " " , "T" ) // Replace SPACE in middle with a `T` to comply with ISO 8601 standard format.
) // Returns a `OffsetDateTime`.
See this code run live at IdeOne.com.
Your input string includes an offset-from-UTC.
But you are trying to parse that as a LocalDateTime. A LocalDateTime has no concept of time zone or offset-from-UTC because it does not represent a moment. So, square peg, round hole. You are discarding valuable information.
Instead you should be parsing as a OffsetDateTime.
Your input string is nearly in standard ISO 8601 format. To comply fully, simply replace the SPACE in the middle with a T.
String input = "2019-02-22 19:29:43+00:00".replace( " " , "T" ) ;
The ISO 8601 formats are used by default by the java.time classes when parsing/generating strings. So no need to specify a formatting pattern.
OffsetDateTime odt = OffsetDateTime.parse( input ) ;
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With