How do I obtain a java.sql.Timestamp that represents 24 hours ago? I'm using JDK 8 via Scala.
Asked
Active
Viewed 2,346 times
0
-
6What have you tried so far, and which version of Java are you using? (I'd do most computations in java.time and then convert from an Instant, personally...) – Jon Skeet Jan 22 '15 at 13:35
-
@JonSkeet I'm on JDK 1.8, via Scala. I'm kind of new to Scala/Java so I'm unsure what to reach for in this case. I remember using Joda in the past however, so thinking of looking into that. – aknuds1 Jan 22 '15 at 13:36
1 Answers
10
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".

Jon Skeet
- 1,421,763
- 867
- 9,128
- 9,194