0

I'm trying to use Joda time to parse a String date time I get from an API response to a long (or Joda DateTime object) so I can store it in a database.

2018-01-13T16:45:33.416400+00:00

Right now what I have is:

DateTimeFormatter f = DateTimeFormat.forPattern("yyyy-MM-dd?HH:mm:ss.??????+??:??");

The parts that have question marks in the pattern I am not sure what to put in. Any ideas?

bycfly
  • 341
  • 3
  • 13
  • I don't think Joda supports microsecond precision. Other than that, you can use the default parser, e.g., `new DateTime("2018-01-13T16:45:33.416400+00:00")`. If you specifically need a `DateTimeFormatter`, you can use `ISODateTimeFormat.dateTimeParser()`. – shmosel Jan 15 '18 at 03:03

1 Answers1

0

tl;dr

java.time.OffsetDateTime.parse( “2018-01-13T16:45:33.416400+00:00” ) 

Microseconds

Your input string represents microseconds. Joda-Time is limited to milliseconds. So, square peg, round hole.

java.time

Use the replacement for Joda-Time, the java.time classes.

OffsetDateTime

The java.time classes such as OffsetDateTime have nanosecond resolution, for up to 9 digits of decimal fraction, more than enough for your microseconds.

Your String happens to comply with the ISO 8601 standard for date-time string formats. The java.time classes use these standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.

OffsetDateTime  odt = OffsetDateTime.parse( “2018-01-13T16:45:33.416400+00:00” ) ;

Database

With a driver supporting JDBC 4.2 or later, you can exchange java.time objects directly with your database.

myPreparedStatement.setObject( … , odt.toInstant() ) ;

…and…

Instant instant = myResultSet.getObject( … , Instant.class ) ;

About java.time

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.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154