How can I create a java.sql.timestamp
without timezone (i´m getting 2007-09-23T10:10:10Z
and I pretend 2007-09-23T10:10:10
).
I try:
Timestamp timestamp = Timestamp.valueOf("2007-09-23 10:10:10");
but in debug i saw that the cdate is 2007-09-23T10:10:10.000+0100
instead of 2007-09-23T10:10:10
… can I create a java.sql.timestamp without timezone …
No, you cannot. Wrong class. Use java.time.LocalDateTime
instead.
A java.sql.Timestamp
is the wrong class to use. It represents a moment in UTC with a resolution of nanoseconds.
If you want a date with time-of-day irrespective of time zone or offset-from-UTC (so, not a moment), use another class that is fit-for-purpose.
By the way… The java.sql.Timestamp
is a terrible old class badly designed, and was supplanted years ago by the class java.time.Instant
(always in UTC) or alternatively java.time.OffsetDateTime
if set to an offset of UTC.
LocalDateTime
The proper class for a date with time-of-day without any concept of time zone or offset-from-UTC is LocalDateTime
.
As noted above, this means this class is not a moment, not a point on the timeline, and should not be used to track actual points of time when an event happened in some place.
TIMESTAMP WITHOUT TIME ZONE
In a SQL-standard compliant database such as Postgres, use a column of data type TIMESTAMP WITHOUT TIME ZONE
(not the WITH
type).
LocalDateTime ldt = myResultSet.getObject( … , LocalDateTime.class ) ;
And…
myPreparedStatement.setObject( … , ldt ) ;
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With