Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java SQL subtract an hour from date

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.

like image 711
djechlin Avatar asked Dec 09 '22 22:12

djechlin


2 Answers

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));
like image 152
Alex Coleman Avatar answered Dec 23 '22 18:12

Alex Coleman


tl;dr

mySqlTimestamp.toInstant()
              .minus( Duration.ofHours( 1 ) )

Avoid old date-time classes

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.

like image 43
Basil Bourque Avatar answered Dec 23 '22 20:12

Basil Bourque