如何提前5年

问题描述 投票:0回答:6

我是 java 8 的新手,我想提前五年,这是我的代码:

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

但是我收到以下错误:

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

谁能帮我怎么做?

java java-8
6个回答
83
投票
ZonedDateTime.now().minusYears(5).toInstant()

这将使用您的默认时区来计算时间。如果您想要另一份,请在

now()
中指定。例如:

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

15
投票

根据 Javadoc,Instant 只接受从纳秒到天的时间单位 Instant.plus(long amountToAdd, TemporalUnit unit);

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


9
投票

Instant不支持YEARS的加减。

如果你只需要日期而不需要时间,你可以使用这个LocalDate:

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

否则您可以使用 LocalDateTime。


1
投票

我遇到了同样的异常,但使用 ChronoUnit.MONTHS。这有点误导,因为在编译时不会抛出错误或警告或其他东西。 无论如何,我也阅读了文档:

并且,是的,不幸的是,所有其他 ChronoUnit 类型均不受支持。

令人高兴的是,LocalDateTime 也可以减去月份和年份。

LocalDateTime.now().minusYears(yearsBack)

LocalDateTime.now().minusMonths(monthsBack);


0
投票

tl;博士

LocalDate                            // Represent a date only, no time, no zone.
.now( 
    ZoneId.of( "America/Edmonton" )  // Today's date varies by zone.
)
.minusYears( 5 )                     // Go back in time by years.
.toString()                          // Generate text is standard format.

运行代码在 Ideone.com

2018-11-20

LocalDate

如果您只需要日期,没有时间和时区,请使用

LocalDate
。要向后移动几年,请致电
minusYears

ZoneId

要捕获当前日期,请指定时区。否则隐式应用 JVM 当前的默认时区。请了解,对于任何特定时刻,*日期会因全球时区而异

Asia/Tokyo
是“明天”,
America/Edmonton
仍然是“昨天”。

ZoneId z = ZoneId.of( "America/Edmonton" ) ;
LocalDate today = LocalDate.now( z ) ;
LocalDate fiveYearsAgo = today.minusYears( 5 ) ;

生成文本

生成的文本是标准的ISO 8601格式。

String output = fiveYearsAgo.toString() ;

-5
投票

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

Instant.now().minus(Period.ofYears(5).getDays(),ChronoUnit.DAYS);
© www.soinside.com 2019 - 2024. All rights reserved.