问题
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?
回答1:
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()
回答2:
According to the Javadoc, Instant will only accept temporal units from nanos to days Instant.plus(long amountToAdd, TemporalUnit unit);
You can use LocalDateTime. You use it the same way, but it will support operation on the YEARS level.
回答3:
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.
回答4:
If you are so inclined is does not require the date time conversion.
Instant.now().minus(Period.ofYears(5).getDays(),ChronoUnit.DAYS);
来源:https://stackoverflow.com/questions/34813693/how-to-get-5-years-before-now