Java 8 How do I get a java.sql.Timestamp that is 24 hours ago?

How do I obtain a java.sql.Timestamp that represents 24 hours ago? I'm using JDK 8 via Scala.

Jon Skeet
people
quotationmark

If you're using Java 1.8, it's as simple as:

Instant instant = Instant.now().minus(24, ChronoUnit.HOURS);
Timestamp timestamp = Timestamp.from(instant);

You can use the overload of now() accepting a Clock to be more test-friendly (so you can test with a fake clock rather than the system clock). You might also want a static import of ChronoUnit.HOURS for readability - i.e. Instant.now().minus(24, HOURS).

Note that this will be exactly 24 hours in the past - not "the same local time, but yesterday".

people

See more on this question at Stackoverflow