How to get 5 years before now
Asked Answered
C

6

65

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?

Carmencarmena answered 15/1, 2016 at 14:49 Comment(4)
Try to specify more precisely what you mean by 5 years ago. A year is not a constant unit of duration. Some years are a bit longer than other years. Do you want the same date as today, 5 years ago? Or do you want 5*365 days ago?Margarine
Invoke new FlyingDelorean().Builder.speed(88).unit(Unit.MILES_PER_HOUR).build();Concent
Related: #39908425Doctorate
Time math ain't easy. Imagine instant corresponds to 13:00 Feb 29, 2012. What should instant.plus(-1, ChronoUnit.YEARS) return? Whatever you think it should return, now think what instant.plus(-1, ChronoUnit.YEARS).plus(1, ChronoUnit.YEARS) return.Midship
R
88
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()
Resplendent answered 15/1, 2016 at 14:57 Comment(0)
R
16

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.

Rutharuthann answered 15/1, 2016 at 15:7 Comment(1)
Thanks for stating what TemporalUnits are supportedMaleki
O
9

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.

Odom answered 15/1, 2016 at 14:57 Comment(2)
Your first sentence is wrong. Instant does NOT support years - and that is why the OP has a problem.Darby
Thnx! It was a typo.Odom
S
1

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: enter image description here

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);

Singley answered 13/1, 2021 at 10:12 Comment(0)
P
0

tl;dr

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.

Run code at Ideone.com.

2018-11-20

For your copy-paste convenience:

LocalDate.now().minusYears( 5 )  // Using JVM’s current default time zone to get today's date.

LocalDate

If you want simply the date, without time-of-day, and without time zone, use LocalDate. To move back in years, call minusYears.

ZoneId

To capture the current date, specify a time zone. If omitted, the JVM’s current default time zone is implicitly applied. Understand that for any given moment, the date varies around the globe by time zone. It's "tomorrow" in Asia/Tokyo while still "yesterday" in America/Edmonton.

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

FYI, see list of real time zone names, with Continent/Region names.

Generate text

Generate text is standard ISO 8601 format.

String output = fiveYearsAgo.toString() ;
Parris answered 21/11, 2023 at 0:15 Comment(0)
A
-6

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

Instant.now().minus(Period.ofYears(5).getDays(),ChronoUnit.DAYS);
Andreeandrei answered 29/6, 2017 at 15:18 Comment(4)
Does not work! Java is so disappointing! Does not even do what it says! Period.ofYears(5).getDays() value is 0Cryptocrystalline
Actually getDays() does exactly what it says. Look at the JavaDoc: The resulting period will have the specified months. The years and days units will be zero.Dustproof
This worked for me: Instant.now().minus(5 * 365L, ChronoUnit.DAYS)Dodecasyllable
You can't know how many days there are in five years with Period.ofYears(5).getDays(). It's a question that doesn't make any sense because you haven't specified which years. It might be a leap year, it might not. The days count would vary.Seed

© 2022 - 2024 — McMap. All rights reserved.