How to update a Timestamp field in MySql from a Java PreparedStatement? - java

My index.html has an <input type="datetime-local"> field and I need to update a MySql database with whatever value the user selects. My database field is currently a Timestamp. How can I create an update statement that allows me to update the database with this datetime-local value? I've tried many options and my current attempt is shown below; however, this does not work. I am doing this all in Java.
String updateStatement = "UPDATE cars SET reservation = ? WHERE uniqueID = ?";
pStmt = con.prepareStatement(updateStatement);
pStmt.setTimestamp(1, reservation);
pStmt.setTimestamp(2, someUniqueId);

tl;dr
To answer your specific code question (but this is the wrong way to handle appointments/reservations):
myPreparedStatement
.setObject(
1 ,
ZonedDateTime
.of
(
LocalDate.of( 2021 , Month.JANUARY , 23 ) ,
LocalTime.of( 15 , 30 ) ,
ZoneId.of( "Africa/Tunis" )
)
.toInstant()
.atOffset( ZoneOffset.UTC )
)
;
java.time
The TIMESTAMP type in MySQL is for tracking a moment, a specific point on the timeline, as seen from an offset of zero hours-minutes-seconds from UTC, resolving to microseconds. This maps to TIMESTAMP WITH TIME ZONE in standard SQL.
The appropriate match in Java would be java.time.Instant. This class also represents a moment as seen in UTC, but with finer resolution of nanoseconds.
Unfortunately, the JDBC 4.2 specification requires support for only one of the three types that track a moment: OffsetDateTime. Both Instant and ZonedDateTime are optional in JDBC 4.2. So your particular JDBC driver may or may not support Instant. This design decision by the JDBC team baffles me. Converting between Instant and OffsetDateTime is utterly simple, and should have been required by JDBC spec.
I am guessing you are letting users pick a date and a time-of-day within a particular time zone. But I'm not sure, as your neglected to detail your inputs.
LocalDate localDate = LocalDate.of( 2021 , Month.JANUARY , 23 ) ;
LocalTime localTime = LocalTime.of( 15 , 30 ) ;
ZoneId zoneId = ZoneId.of( "America/Edmonton" ) ;
ZonedDateTime zdt = ZonedDateTime.of( localDate, localTime , zoneId ) ;
To store in the database, let's adjust from a time zone to UTC (an offset of zero). Convert from ZonedDateTime to Instant, and then to OffsetDateTime with an offset of zero hours-minutes-seconds represented by the constant ZoneOffset.UTC.
OffsetDateTime odt = zdt.toInstant().atOffset( ZoneOffset.UTC ) ; // Use `OffsetDateTime` rather than `Instant` for maximum compatibility across JDBC 4.2 drivers.
Do not call PreparedStatement#setTimestamp. That method is now legacy, for the terrible java.sql.Timestamp class. Never use date-time classes outside the java.time package. Those legacy classes were supplanted years ago by the modern java.time classes defined in JSR 310.
Call PreparedStatement#setObject. The JDBC team has yet to define specific set… methods for the various java.time classes. Again, a design decision which baffles me. However, we can exchange the java.time objects using setObject/getObject.
myPreparedStatement.setObject( … , odt ) ;
Retrieval.
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
Tracking appointments
By the way, you mentioned the business problem is making restaurant reservations in the future. For this work, you are taking the wrong approach.
Such future appointments are not tracked as moments, are not specific points on the timeline. If politicians were to change the offset used by that time zone, your customers expect a restaurant reservation for 7 PM to stay at 7 PM, regardless of politicians moving the clock forward or backward. Similarly, a dental appointment for 3 PM four months from now should stay at 3 PM even if the politicians change the offset. And politicians around the world do enjoy changing their time zone offset. This happens surprisingly often, and with less and less forewarning.
Reservations/appointments should be tracked as date and time without time zone, storing time zone separately in second column of database. These types would be TIMESTAMP WITHOUT TIME ZONE in standard SQL, and DATETIME in MySQL. And use a text type for the time zone identifier. The matching type in Java would be LocalDateTime and ZoneId. At runtime for calendaring, combine to determine a moment with a ZonedDateTime.
I and other authors have covered this many times already on Stack Overflow. So search to learn more.
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. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 brought some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android (26+) bundle implementations of the java.time classes.
For earlier Android (<26), a process known as API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….

Maybe your date format is incorrect.
reservation = System.currentTimeMillis();
UPDATE
Ok,I understand you.You should use String to receive the datetime-local value.
Because the format of datetime-local from frontend is yyyy-MM-ddTHH:mm, but the format of TimeStamp in Java(package java.sql) is yyyy-MM-ddTHH:mm:ss.
It lack the :ss, so can not receive.
Finally set timestamp after convert String to TimeStamp.
datetimeLocal = datetimeLocal.replaceAll("T", " ") + ":00";
Timestamp reservation = Timestamp.valueOf(datetimeLocal);

Related

LocalDateTime to Mysql DATETIME converts actual date to actual date+5.30

I am having a model with multiple member variables in that:
One with LocalDateTime type.
#Column(name = "localdatetime_field")
private LocalDateTime updatedAt;
Other with timestamp:
#Column(name = "timestamp_field")
private Timestamp addedAt;
The problem is:
When I save data in the DB, with mysql-connector v8.0.18:
-> It keeps the data of Localdatetime & Timestamp same as given.
with mysql-connector v5.1.34:
-> It changes the data of Localdatetime by +5.30.
I wonder is it because of mysql-connector or some jackson convertor working behind the scenes.
Avoid legacy date-time classes
The java.sql.Timestamp class is obsolete, supplanted years ago by the modern java.time classes defined in JSR 310.
java.time
Not a moment
The LocalDateTime class is appropriate only to database columns of a type akin to the SQL-standard type TIMESTAMP WITHOUT TIME ZONE. These types do not represent a moment, cannot be a point on the timeline. Without the context of a time zone or offset-from-UTC, we cannot know if noon on the 23rd is noon in Tokyo Japan, noon in Toulouse France, or noon in Toledo Ohio US — three different moments, several hours apart.
In the context of most business app, these types are not usually appropriate. If recording when something has happened, these are the wrong types. These types are only good for (a) describing something across all time zones such as when Christmas starts (different moments in various time zones), and (b) booking appointments in the future that should remain at a certain wall-clock time even if politicians change the time zone rules in than region (Ex: dental appointment at 3 PM should stay at 3 PM even if politicians push the clock forward or backward an hour).
A moment
For database columns of a type akin to the SQL-standard type TIMESTAMP WITH TIME ZONE, we would use either Instant, OffsetDateTime, or ZonedDateTime. Oddly, the JDBC 4.2 spec requires support only for the second of those three: OffsetDateTime.
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
Writing to the database:
myPreparedStatement.setObject( … , odt ) ;
If you want to see the returned OffsetDateTime in the time zone of your choice, apply a ZoneId to get a ZonedDateTime. Be sure to use a real time zone name in format of Continent/Region. Never use 2-4 character pseudo-zones such as IST, EST, and such.
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = odt.atZoneSameInstant( z ) ;
Beware of middleware
Unfortunately, middleware and tooling often feels the need to inject a time zone adjustment into your date-time info. Most databases store a moment as UTC (an offset from UTC of zero hours-minutes-seconds). Yet some tooling will retrieve that UTC value, apply a time zone adjustment, and then report the result. This anti-feature clouds the picture of what was actually stored in the database.
To get around that anti-feature, you will need to study the documentation for your particular middleware or tool. You may be able to shut off the adjustment. Or as a workaround, you may need to set its applied time zone to be UTC/GMT, or in a pinch use the zone Atlantic/Reykjavik which happens to use zero as its offset.
If doing straight JDBC with the java.time classes, I expect you will see no such rude injection of time zone. At least I have not heard of any such behavior with any JDBC driver yet.
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. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 brought some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android (26+) bundle implementations of the java.time classes.
For earlier Android (<26), the process of API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….

Change the time based on the gmt area on Android

I'm a beginner in android development and I've been searching for hours to find an answer for my question but I didn't really understand anything I found.
The match between 2 teams is starting at 20:00 gmt and I want to make it + - based on the area. For example in germany +1 gmt the time should be 21:00. I only want the hours and minutes format like that.
tl;dr
OffsetDateTime
.of(
LocalDate.of( 2021 , Month.MARCH , 23 ) ,
LocalTime.of( 20 , 0 ) ,
ZoneOffset.UTC
) // Returns a `OffsetDateTime` object.
.atZoneSameInstant(
ZoneId.of( "Europe/Berlin" )
) // Returns a `ZonedDateTime` object.
.toLocalTime() // Returns a `LocalTime` object.
.toString() // Returns a `String` object, with text in standard ISO 8601 format.
21:00
Details
Location does not necessarily correlate to time zone. Users choose their time zone as a preference. Servers should generally be set to UTC (an offset of zero). You can get the JVM’s current default time zone by calling ZoneId.systemDefault. If crucial, you should explicitly ask the user to confirm their desired zone.
I only want the hours and minutes format like that.
Date-time objects are not text, and do not have a "format". Think in terms of the logic needed for handling date-time values rather than in terms of manipulating strings.
starting at 20:00 gmt and I want to make it + - based on the area
Representing that 8 PM in UTC (the new GMT):
LocalDate tomorrow = LocalDate.now( ZoneOffset.UTC ).plusDays( 1 ) ;
LocalTime eightPM = LocalTime.of( 20 , 0 ) ;
OffsetDateTime odt = OffsetDateTime.of( tomorrow , eightPM , ZoneOffset.UTC ) ;
For example in germany +1 gmt the time should be 21:00
Define your desired time zone.
ZoneId z = ZoneId.of( "Europe/Berlin" ) ;
Adjust from the OffsetDateTime to a ZonedDateTime.
ZonedDateTime zdt = odt.atZoneSameInstant( z ) ;
See that code run live at IdeOne.com.
odt.toString(): 2021-02-17T20:00Z
zdt.toString(): 2021-02-17T21:00+01:00[Europe/Berlin]
The odt & zdt objects seen here both refer to the very same simultaneous moment, the same point on the timeline.
This has all been covered many times before on Stack Overflow. Search to learn more.
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. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 brought some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android (26+) bundle implementations of the java.time classes.
For earlier Android (<26), a process known as API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….
It's not Android specific but just a general question about Java.
Use Calendar and SimpleDateFormat like this:
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("GMT"));
calendar.set(2021, 1, 16, 20, 00, 00); // 2021-02-16T20:00:00 GMT
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT+01:00"));
System.out.println(simpleDateFormat.format(calendar.getTime()));
Set (input) your date as GMT. Then format it GMT+01:00 with SimpleDateFormat and print (output) it.

Store date and time from Java in SQL SERVER

I am trying to store datetime from Java using GregorianCalendar class in SQL SERVER, however it only stores date. I need to store the date and time in SQL SERVER.
this is the code i implemented
CallableStatement asignarTurno=conexionBBDD
.getConexionBBDD().prepareCall("{call asignarTurno(?,?,?,?,?,?)}");
//GregorianCalendar(int year, int month, int dayOfMonth, int hourOfDay, int minute, int second)
GregorianCalendar h=new GregorianCalendar(2000, 1, 1, 8, 30,0);
java.sql.Date date = new java.sql.Date(h.getTimeInMillis());
asignarTurno.setInt(1,1);
asignarTurno.setDate(2,date);
asignarTurno.setDate(3,date);
asignarTurno.setDate(4,date);
asignarTurno.setString(5, "000");
asignarTurno.setString(6,"0001");
asignarTurno.execute();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
Multiple problems with your code.
Never use the terrible date-time classes such as GregorianCalendar and Date. These were supplanted years ago by the modern java.time classes defined in JSR 310.
You are trying to represent a moment having a date, a time-of-day, and an implicit time zone (GregorianCalendar) into a data type that pretends to hold only a date (java.sql.Date). Square peg, round hole.
Date-only
The DATE type in Microsoft SQL Server is akin to the SQL-standard type DATE, holding only a date, without a time-of-day, and without a time zone. So use java.time.LocalDate in Java.
LocalDate ld = LocalDate.of( 2000 , Month.FEBRUARY , 1 ) ;
myPreparedStatement.setObject( … , ld ) ;
And retrieval.
LocalDate ld = myResultSet.getObject( … , LocalDate.class ) ;
Moment
If you do indeed want to track moments, you must redefine your database column with an appropriate data type. In standard SQL, that would be TIMESTAMP WITH TIME ZONE. In Microsoft SQL Server, that would be datetimeoffset.
In Java, you would place your date at time-of-day in the context of a time zone. This produces a ZonedDateTime object.
LocalDate ld = LocalDate.of( 2000 , Month.FEBRUARY , 1 ) ;
LocalTime lt = LocalTime.of ( 8 , 30 ) ;
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
Unfortunately, the JDBC 4.2 team inexplicably decided to require support for OffsetDateTime but not the two more commonly-used classes, Instant and ZonedDateTime. So for maximum portable code, use OffsetDateTime. If portability is not so important, test your JDBC driver to see if it optionally chose to support ZonedDateTime or Instant.
We could just call ZonedDateTime#toOffsetDateTime. But this would bring the offset used by that time zone at that moment. For clarity, I suggest instead adjusting to UTC. That is easily accomplished by extracting a Instant (always in UTC) from our ZonedDateTime. Then we convert to OffsetDateTime with an offset of zero, per JDBC 4.2 spec.
OffsetDateTime odt = zdt.toInstant().atOffset( ZoneOffset.UTC ) ;
Then pass to your prepared statement.
myPreparedStatement.setObject( … , odt ) ;
And retrieval.
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
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. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 brought some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android (26+) bundle implementations of the java.time classes.
For earlier Android (<26), a process known as API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….

Schedule that runs every day at a specific time with hh:mm:ss

I'm trying to run code at a specific time every day, but with hh:mm:ss. I'm specifically, trying to run it at 5PM EST every day, so Timezones needs to be accounted for.
Here's my attempt, in kotlin:
val timer = Timer()
val format = SimpleDateFormat("hh:mm:ss")
val date = format.parse("11:07:09")
timer.schedule(object : TimerTask() {
override fun run() {
// code here
}
}, date)
I wasn't able to get that working, and even if I did, I'm not sure how I'd add timezones to it as well.
How can I do this?
tl;dr
java.util.Date
.from(
ZonedDateTime.of(
LocalDate.now( ZoneId.of( "America/Montreal" ) ) ,
LocalTime.parse( "11:07:09" ) ,
ZoneId.of( "America/Montreal" )
)
.toInstant()
)
Details
A java.util.Date represents a date with a time-of-day in UTC.
You have ignored the date and the zone/offset.
Your result is apparently defaulting to 11 AM on January 1, 1970.
java.time
Also, the terrible Date and SimpleDateFormat classes were supplanted years ago by the java.time classes.
Represent your target time-of-day.
LocalTime lt = LocalTime.parse( "11:07:09" ) ;
Get current date, today’s date. Requires a time zone. For any given moment, the date varies around the globe by zone.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
LocalDate today = LocalDate.now( z ) ;
Put these together to determine a moment.
ZonedDateTime zdt = ZonedDateTime.of( today , lt , z ) ; // Time-of-day will be adjusted if not valid on that date in that zone.
Adjust into UTC. Same moment, same point on the timeline, different wall-clock time.
Instant instant = zdt.toInstant() ; // Adjust from zone to UTC.
Avoid the legacy date-time classes. But if you must interoperable, you can convert back and forth by calling new methods added to the old classes.
java.util.Date d = java.util.Date.from( instant ) ;
You will likely want to improve this code to see if your desired moment has already passed. To compare, use isAfter and isBefore methods.
Executors
The Timer class has been supplanted by the executor framework. Search the Oracle Java Tutorials and Stack Overflow to learn more.
With an executor, you can schedule a task to run at a certain moment. But you do so indirectly, by specifying a waiting period rather than a time-of-day. The scheduling executor takes an argument for an initial delay. You can calculate that delay as a span of time between the current moment and the desired moment.
To calculate that span of the time, use the Duration class.
Duration d = Duration.between( Instant.now() , instant ) ;
Keep in mind that you cannot expect split-second perfect timing of your tasks to be executed. The scheduling of your JVM on the host OS, and of your Java threads within the JVM, can involve delays.
Of course, you will also need to record a history of your tasks when completed. When your app does a shutdown, then relaunch, it needs to study the history to figure out how to set up a new schedule. This issue is beyond the scope of this Answer. Read up on writing files, using a database, or relying on some other persistence scheme.
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.
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?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
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.

convert a unix timestamp to a postgres equivalent timestamp in java

I have a field in postgres
Column | Type
created_at | timestamp without time zone
I have a unix timestamp stored in long in Java
long createdAtTime = data.getcreatedAtTime();
I want to convert it to timestamp in java so that I can store with activejdbc into postgres
I tried the following
Date convertedTime = new Date(createdAtTime*1000L);
record.set("created_at", convertedTime);
record.saveIt();
But I get the following error:
Can't infer the SQL type to use for an instance of java.util.Date. Use setObject() with an explicit Types value to specify the type to use.
Should I be using a different way to convert the date first?
java.sql.Timestamp timestamp = new Timestamp(createdAtTime*1000L);
record.set("created_at", convertedTime);
record.saveIt();
Instead of util you have tried with java.sql.Date.
Its a native type of SQL.
Incompatible types
I have a field in postgres …
timestamp without time zone …
…and…
I have a unix timestamp stored in long in Java
long createdAtTime = data.getcreatedAtTime();
This is a contradiction.
The SQL-standard type TIMESTAMP WITHOUT TIME ZONE purposely lacks any indicator of time zone or offset-from-UTC. As such, this type does not represent a moment, is not a point on the timeline. This type represents potential moments along a range of about 26-27 hours, the range of time zones around the globe.
If you are trying to track specific moments, use the other SQL-standard type, TIMESTAMP WITH TIME ZONE. In Postgres, all values of this type are stored in UTC (an offset of zero). If you pass a value indicating some other offset or time zone, Postgres adjusts the value to UTC before storing.
When retrieving a value from a column of type TIMESTAMP WITH TIME ZONE in Postgres, you are always getting a value in UTC. Unfortunately, some well-intentioned tools or drivers sitting between you and the database may decide the dynamically apply a time zone to the value. While well-intentioned, I consider this quite the anti-feature. This behavior creates the illusion of a time zone stored in the database while in fact Postgres only stores UTC in this type.
Date convertedTime = new Date(createdAtTime*1000L);
The java.util.Date class is terrible, poorly designed and flawed. Never use this class nor its siblings, Calendar, SimpleDateFormat, and such. These are all legacy now, supplanted years ago by the modern java.time classes defined in JSR 310.
Instant
The Instant class takes over for java.util.Date. Both classes represent a moment in UTC, though Instant has a finer resolution of nanoseconds versus milliseconds.
unix timestamp stored in long in Java
If you have a count of whole seconds from the epoch reference of the first moment of 1970 in UTC, 1970-01-01T00:00:00Z, convert to an Instant.
Instant instant = Instant.ofEpochSecond( 1_539_555_140L ) ;
Tip: Do not make a habit of tracking time as a count-from-epoch. This is ambiguous (different systems use different resolutions and different epoch references), error-prone, and makes debugging/logging treacherous. Use java.time objects and standard ISO 8601 strings for representing date-time values.
Your JDBC driver may be able to accept an Instant.
myPreparedStatement.setObject( … , instant ) ;
Retrieval:
Instant instant = myResultSet.getObject( … , Instant.class ) ;
OffsetDateTime
If not supporting Instant, use convert to OffsetDateTime. Any JDBC 4.2 or later driver is required to support OffsetDateTime.
OffsetDateTime represents a date and time-of-day with an offset-from-UTC. In contrast, Instant is fixed at UTC, serving as a basic building-block class in java.time framework. Also, OffsetDateTime is more flexible with abilities such as generating strings in various formats versus Instant using only standard ISO 8601 format.
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;
myPreparedStatement.setObject( … , odt ) ;
Retrieval:
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
…or…
Instant instant = myResultSet.getObject( … , OffsetDateTime.class ).toInstant() ;
LocalDateTime
If you are not trying to represent moments, such as database type TIMESTAMP WITHOUT TIME ZONE, use the LocalDateTime class.
But if you are thinking use of these types is somehow avoiding the work of using time zones in tracking moments, you are sorely mistaken. This is a “pay now or pay later” situation: Either learn basic date-time concepts and handling practice now, or desperately wrestle with a horrible mess of failed data later.
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.
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?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
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.
I see that your Database column stores value as time stamp without time zone,
why don't you try this
Timestamp current = Timestamp.from(Instant.now());
record.set("created_at", current);//I don't know if you might need to parse
record.saveIt();

Categories