Search code examples
javatimestampsql-timestamp

Subtract 3 weeks from current timetamp


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


Solution

  • 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));
    

    Ideone demo

    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);
    

    Ideone demo