javajava-8

How to get 5 years before now


I am new to java 8 and I am trying to get five years before now, here is my code:

Instant fiveYearsBefore = Instant.now().plus(-5,
                    ChronoUnit.YEARS);

But I get the following error:

java.time.temporal.UnsupportedTemporalTypeException: Unsupported unit: Years

Can anyone help me how to do that?


Solution

  • ZonedDateTime.now().minusYears(5).toInstant()
    

    That will use your default time zone to compute the time. If you want another one, specify it in now(). For example:

    ZonedDateTime.now(ZoneOffset.UTC).minusYears(5).toInstant()