I need a java.sql.Timestamp
value corresponding to one hour ago. I have a few date related things happening here so it's important that the current time is sampled only once and the rest of the code uses that same time. As far as setting a Timestamp
based on current time in ms.
Manipulating the Calendar
object seems really klunky since I have to do things like add and subtract time to the calendar, which modifies it, so then I would have the lovely pleasure of either cloning myself a copy first or toggling its value around.
Simply subtract an hour off of the current time in milliseconds when making your timestamp (1 hour = 60 * 60 * 1000 ms)
Timestamp oneHourAgo = new Timestamp(System.currentTimeMillis() - (60 * 60 * 1000));
mySqlTimestamp.toInstant()
.minus( Duration.ofHours( 1 ) )
The java.sql types are intended only for exchanging data with a database. Do not use these for business logic.
The troublesome old date-time classes are now supplanted by the java.time classes. The java.time equivalent of java.sql.Timestamp
is java.time.Instant
. You can even convert to/from via new methods added to the old classes.
Instant instant = mySqlTimestamp.toInstant();
You can then subtract an hour represented by a Duration
.
Duration d = Duration.ofHours( 1 );
Instant hourPrior = instant.minus( d );
Note that these classes follow Immutable Objects pattern. Rather than modifying (“mutating”) parts of the values in the object, a new object is instantiated based on the values of the original. So no problem with side-effects discussed in another answer. And automatically thread-safe.
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