What is a timestamp?
Wikipedia defines a timestamp as
a sequence of characters or encoded information identifying when a
certain event occurred …
So your string is not a timestamp or at least can only be considered one if we know which time zone (or UTC offset) is assumed for the date and time of day it contains. Today most IT systems are not confined to one time zone, so it is generally recommended to include UTC offset information with your timestamps and/or keep them in UTC. I am assuming that you asked for an old-fashioned java.sql.Timestamp
for use with your SQL database. Depending on your adherence to the recommendations you will need different types both in SQL and in Java.
- Recommended: Use explicit offset, preferably UTC. With most database engines this means using its
timestamp with time zone
or timestamptz
data type. The JDBC standard since 4.2 says that you should then use OffsetDateTime
in Java. Many drivers also handle Instant
, the class we would normally prefer for an unambiguous timestamp in Java. Your attempt to create an Instant
may hint that this agrees with your intentions.
- Not recommended: Use implicit offset, preferably UTC. Many old applications would use their own time zone. In any case use
timestamp
(without time zone) in SQL and LocalDateTime
in Java. The lack of offset in your string may hint that this was your approach.
The java.sql.Timestamp
class that you mentioned is poorly designed, in fact a true hack on top of the already poorly designed java.util.Date
class. So Timestamp
is not among the classes I recommend for sending your tiemstamp value to the database, whether for storage or for use in a query.
Saving your timestamp to SQL
Here’s a code example using OffsetDateTime
and a custom assumed time zone.
String myTime = "2020-08-03T20:15:49";
OffsetDateTime odt = LocalDateTime.parse(myTime)
.atZone(ZoneId.of("Asia/Colombo"))
.toOffsetDateTime();
PreparedStatement ps = yourDatabaseConnection
.prepareStatement("insert into your_table(your_timestamptz_column) values (?);");
ps.setObject(1, odt);
ps.executeUpdate();
Since JDBC 4.2 the setObject
method accepts java.time types including OffsetDateTime
.
If your time string is UTC, the conversion to OffsetDateTime
is a bit simpler:
OffsetDateTime odt = LocalDateTime.parse(myTime).atOffset(ZoneOffset.UTC);
Using Instant
: You may convert the OffsetDateTime
from before simply:
Instant inst = odt.toInstant();
Now you can pass inst
to setObject()
in the same way that we passed odt
before.
If you are using timestamp
without time zone in SQL and LocalDateTime
in Java, the answer by Arvind Kumar Avinash already shows the simple way to parse your string. Also a LocalDateTime
can be passed to setObject()
in the same way as above.
By the way, we most often neither need to nor want to use the TemporalAccessor
interface. Its documentation says:
This interface is a framework-level interface that should not be
widely used in application code. …