Opencsv map iso 8601 to java.SQL Timestamp

49 Views Asked by At

My data is of format '2023-12-20T23:15:49.680Z'. This looks like ISO 8601.

I need to convert this to a java.sql TimeStamp.

I tried using this and a few other formats, none of which work: @CsvDate(value = "yyyy-MM-dd'T'HH:mm:ss")

org.apache.commons.beanutils.ConversionException: String must be in JDBC format [yyyy-MM-dd HH:mm:ss.fffffffff] to create a java.sql.Timestamp

What is the correct format to use?

1

There are 1 best solutions below

0
Basil Bourque On

I need to convert this to a java.sql TimeStamp

No, you don’t.

That terribly flawed class Timestamp was years ago supplanted by the modern java.time classes defined in JSR 310.

Parse your ISO 8601 compliant string as a java.time.Instant object.

Instant instant = Instant.parse( "2023-12-20T23:15:49.680Z" ) ;

The Z on the end of your input string means an offset from UTC of zero hours-minutes-seconds. Pronounced “Zulu”. The Instant class has the same meaning, representing a moment with an offset of zero.

To create a String with text in that ISO 8601 format, call toString.

String output = instant.toString() ;

If you need to interoperate with old code not yet updated to java.time, call the new conversion methods added to the old classes.

java.sql.Timestamp ts = Timestamp.from( instant ) ;

When you receive a java.sql.Timestamp object, immediately convert to an Instant.

Instant instant = ts.toInstant() ;

But avoid the legacy dae-time classes wherever possible. They really are the bad.

You said:

String must be in JDBC format [yyyy-MM-dd HH:mm:ss.fffffffff] to create a java.sql.Timestamp

No, it does not. Use Instant rather than Timestamp and all your problems go away.

What is the correct format to use?

Always use ISO 8601 formats when exchanging date-time data as text.