java 如何获得 5 年前的现在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34813693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 23:24:18  来源:igfitidea点击:

How to get 5 years before now

javajava-8

提问by Hamed Minaee

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

我是 Java 8 的新手,我试图在五年前获得,这是我的代码:

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?

任何人都可以帮助我如何做到这一点?

回答by JB Nizet

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:

这将使用您的默认时区来计算时间。如果您想要另一个,请在now().例如:

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

回答by pca

According to the Javadoc, Instant will only accept temporal units from nanos to days Instant.plus(long amountToAdd, TemporalUnit unit);

根据 Javadoc,Instant 只接受从 nanos 到天数的时间单位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.

您可以使用LocalDateTime。您以相同的方式使用它,但它将支持 YEARS 级别的操作。

回答by Milan

Instant does not support addition or subtraction of YEARS.

Instant 不支持 YEARS 的加减。

You can use this LocalDate if you only need date without time:

如果您只需要日期而不需要时间,则可以使用此 LocalDate:

LocalDate date = LocalDate.now();
date = date.plus(-5, ChronoUnit.YEARS);

Otherwise you can user LocalDateTime.

否则,您可以使用 LocalDateTime。

回答by Usman Ismail

If you are so inclined is does not require the date time conversion.

如果您愿意,则不需要日期时间转换。

Instant.now().minus(Period.ofYears(5).getDays(),ChronoUnit.DAYS);