How to get 5 years before now
JavaJava 8Java Problem Overview
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?
Java Solutions
Solution 1 - Java
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()
Solution 2 - Java
According to the Javadoc, Instant will only accept temporal units from nanos to days [Instant.plus(long amountToAdd, TemporalUnit unit);][1]
You can use [LocalDateTime][2]. You use it the same way, but it will support operation on the YEARS level.
[1]: https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html#plus-long-java.time.temporal.TemporalUnit- "Instant.plus(long amountToAdd, TemporalUnit unit)" [2]: https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html
Solution 3 - Java
Instant does not support addition or subtraction of YEARS.
You can use this LocalDate if you only need date without time:
LocalDate date = LocalDate.now();
date = date.plus(-5, ChronoUnit.YEARS);
Otherwise you can user LocalDateTime.
Solution 4 - Java
I bumped into the same exception, but with ChronoUnit.MONTHS. It is a little bit misleading, because on compile time does not throw an error or warning or something. Anyway, I read the documentation, too:
and, yes, all the other ChronoUnit types are not supported unfortunately.
Happily, LocalDateTime can substract months and years, too.
> LocalDateTime.now().minusYears(yearsBack)
> LocalDateTime.now().minusMonths(monthsBack);
Solution 5 - Java
If you are so inclined is does not require the date time conversion.
Instant.now().minus(Period.ofYears(5).getDays(),ChronoUnit.DAYS);