0

I have the following timestamp in String format

2019-04-06T00:43:21+00:00
2019-04-04T21:24:33+00:00
2019-04-04T21:02:16+00:00

How can I parse the timestamp strings above to Java.sql.timestamp?

Arya
  • 8,473
  • 27
  • 105
  • 175
  • 1
    I recommend you don’t use `java.sql.Timestamp`. That class is poorly designed and confusing and long outdated. For use with an SQL database depending on the SQL datatype and your JDBC driver’s capabilities instead use either `Instant`, `OffsetDateTIme` or `LocalDateTime`, all from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Apr 06 '19 at 18:53

2 Answers2

2

Use DateFormat to parse your String.

 try{
     String x="2019-04-04T21:24:33+00:00";
     DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssX");
     Date date = (Date) df.parse(x);
     java.sql.Timestamp timeStamp = new java.sql.Timestamp(date.getTime());
 }catch(ParseException pe){
     pe.printStackTrace();
 }

As mentioned by others in comments, there is a more updated way to do this.

String time="2019-04-04T21:02:16+00:00";
OffsetDateTime odt=OffsetDateTime.parse(time,DateTimeFormatter.ISO_OFFSET_DATE_TIME);
java.sql.Timestamp timestamp=new java.sql.Timestamp(odt.toEpochSecond()*1000);
Sandeep Polamuri
  • 609
  • 4
  • 10
  • https://stackoverflow.com/questions/12781273/what-are-the-date-formats-available-in-simpledateformat-class – Sandeep Polamuri Apr 06 '19 at 17:11
  • 2
    These terrible classes were supplanted years ago by the modern *java.time* classes as of the adoption of JSR 310. Suggesting `Date`, `Timestamp`, and `SimpleDateFormat` in 2019 is poor advice. – Basil Bourque Apr 06 '19 at 18:38
  • 2
    Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. Today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. – Ole V.V. Apr 06 '19 at 18:56
2

tl;dr

Timestamp                                   // Avoid this terrible legacy class if possible. Represents a moment in UTC. 
.from(                                      // Convert from modern `Instant` to legacy `Timestamp`. No data loss, as both resolve to nanoseconds.
    OffsetDateTime                          // Modern way to represent a moment with an offset-from-UTC (hours, minutes, and seconds).
    .parse( "2019-04-06T00:43:21+00:00" )   // Parse standard ISO 8601 strings. Returns a `java.time.OffsetDateTime` object.
    .toInstant()                            // Extract an `Instant` from the `OffsetDateTime`, thereby adjusting to UTC (an offset of zero). 
)                                           // Returns a `Timestamp` object, if needed to interoperate with old code not yet updated to *java.time*. 

Even better, skip the terrible Timestamp class entirely.

myPreparedStatement.setObject(                           // As of JDBC 4.2 and later, exchange *java.time* objects with your database.
    1 ,                                                  // Specify the nth placeholder in your SQL statement. 
    OffsetDateTime.parse( "2019-04-06T00:43:21+00:00" )  // Parse an ISO 8601 compliant string as a `OffsetDateTime` object, a moment with an offset-from-UTC. Pass to the database via the `setObject` call.
)

OffsetDateTime

Your input strings indicate an offset-from-UTC (a number of hours-minutes-seconds), that part at the end.

Your input strings are in standard ISO 8601 format. The java.time classes use these formats by default in parsing/generating strings. So no need to specify a formatting pattern.

OffsetDateTime odt = OffsetDateTime.parse( "2019-04-06T00:43:21+00:00" ) ;

java.sql.Timestamp

Never use java.util.Timestamp. That terrible class was supplanted years ago by the modern java.time classes.

If you must have a Timestamp object to interoperate with old code not yet updated to java.time, convert by calling new methods added to the old classes. Extract a Instant from the OffsetDateTime (thereby adjusting from any offset to an offset of zero, for UTC itself). Pass the Instant object to Timestamp.from.

java.sql.Timestamp ts = Timestamp.from( odt.toInstant() ) ;

JDBC 4.2

As of JDBC 4.2, we can exchange java.time objects with the database.

myPreparedStatement.setObject( … , odt ) ;

Retrieval.

OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;

All this has been covered many many times already on Stack Overflow. So search for more info. And in the future, search thoroughly before posting.


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.

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.

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