How to get 5 years before now

人盡茶涼 提交于 2020-01-29 04:16:30

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!