How can I get the current timestamp - x number of weeks using java.sql.Timestamp;
This is my current timestamp Timestamp.from(Instant.now(clock));
x- could be any number from 0-5
How can I get the current timestamp - x number of weeks using java.sql.Timestamp;
This is my current timestamp Timestamp.from(Instant.now(clock));
x- could be any number from 0-5
Seeing the code provided, I would suggest to subtract the weeks from the Instant via Instant::minus. Since ChronoUnit.WEEKS is not supported by Instant::minus, we can convert the weeks in days by multiplying them with 7.
If changing the Instant is not an option, we could convert the Timestamp into an Instant, subtract, and convert back:
Timestamp.from(timestamp.toInstant().minus(x * 7L, ChronoUnit.DAYS));
Or, if you are a friend of Optionals:
Optional.of(timestamp)
.map(Timestamp::toInstant)
.map(t -> t.minus(x * 7L, ChronoUnit.DAYS))
.map(Timestamp::from);
Using Instant Directly example, using local time:
Instant.now(Clock.systemDefaultZone()).minus(numberOfWeeks * 7L, ChronoUnit.DAYS);
Used in context:
public static void main(String[] args) {
Instant now = Instant.now(Clock.systemDefaultZone());
System.out.println("The time right now (local time): " + Timestamp.from(now));
long numberOfWeeks = 3L;
Instant minusXweeks = now.minus(numberOfWeeks * 7L, ChronoUnit.DAYS);
System.out.println("The time 3 weeks before now (local time): " + Timestamp.from(minusXweeks));
}
Output:
The time right now (local time): 2020-08-20 23:24:58.077223
The time 3 weeks before now (local time): 2020-07-30 23:24:58.077223
NOTE:
Why not use ChronoUnit.WEEKS directly? See below:
Instant.now(Clock.systemDefaultZone()).minus(numberOfWeeks, ChronoUnit.WEEKS)
Seems like ChronoUnit.WEEKS is not supported by method java.time.Instant.minus while enum ChronoUnit.DAYS is. When using ChronoUnit.WEEKS in method java.time.Instant.minus then following exception is thrown:
Exception in thread "main" java.time.temporal.UnsupportedTemporalTypeException: Unsupported unit: Weeks
at java.base/java.time.Instant.plus(Instant.java:861)
at java.base/java.time.Instant.minus(Instant.java:978)
at TestClass.main(TestClass.java:18)
To subtract x weeks from the current time of the calendar, you can also try:
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, - (7 * no_of_weeks))