TL;DR
- Avoid the
Timestamp
class if you can. It’s poorly designed and long outdated.
- To answer your questions, no, a
Timestamp
hasn’t got, as in cannot have a format (the same holds true for its modern replacement, Instant
(or LocalDateTime
)).
- Under all circumstances avoid
SimpleDateFormat
and Date
. The former in particular is notoriously troublesome, and both are long outdated too.
Don’t put a format into your model class
You should not want an Instant
nor a Timestamp
with a specific format. Good practice in all but the simplest throw-away programs is to keep your user interface apart from your model and your business logic. The value of the Instant
object belongs in your model, so keep your Instant
or Timestamp
there and never let the user see it directly. I hope that it’s clear to you that 2018-12-30 09:54
and 2018-12-30 09:54:00.0
represent the same value, the same Timestamp
. Just like 17, 0017 and 0x11 represent the same integer value. When you adhere to what I said, it will never matter which format the Instant
has got.
Whenever the user should see the date and time, this happens in the UI, not in the model. Format it into a String
and show the string to the user. Similarly if you need a specific format for persistence or exchange with another system, format the Instant
into a string for that purpose.
java.time and JDBC 4.2
Also for exchange with your database over JDBC, provided that you’ve got a JDBC 4.2 compliant driver, prefer to use a type from java.time over Timestamp
. If the datatype on the database side is timestamp with time zone
, very clearly recommended for a timestamp, pass an OffsetDateTime
like
OffsetDateTime dateTime = yourInstant.atOffset(ZoneOffset.UTC);
yourPreparedStatement.setObject(4, dateTime);
Use setObject
, not setTimestamp
. Some drivers accept the Instant
directly, without conversion to OffsetDateTime
. If on the database side you need a mere timestamp
(without time zone), use LocalDateTime
in Java instead and pass one to setObject
in the same way as above.
PS There are errors in your format pattern string
In a format pattern string, uppercase YYYY
is for week based year and only useful with a week number. For year use either uuuu
or lowercase yyyy
. Similarly lowercase hh
is for hour within AM or PM from 01 through 12 and only useful with an AM or PM marker. For hour of day from 00 through 23 you need uppercase HH
. These errors will give you incorrect dates and times in most cases. Using the wrong case of format pattern letters is a very common mistake. SimpleDateFormat
generally doesn’t mind, it just gives incorrect results. The modern DateTimeFormatter
does a somewhat better job of notifying you of such errors.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Related questions