-4

I have an int representing the year 2022, and I want to create an Instant object representing the first instant of the year, meaning: 2022-01-01 00:00:00.

int year = 2022;

Instant instant = ...

How can we do that in java 8?

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Hamza LAHLOU
  • 69
  • 1
  • 6
  • Unrelated, but Java 8 is quite old already. Consider upgrading, if possible. Latest version is 19. – Zabuzard Oct 07 '22 at 11:04
  • @Zabuzard - The latest LTS version (17) would be a better choice than 19 ... unless the OP is happy to upgrade Java versions every 6 months on average. – Stephen C Oct 07 '22 at 11:07
  • Thank you guys, that was very helpful. If it was up to me I would upgrade to more recent of Java, but the client's app is running on java 8 so I need to work with that version. – Hamza LAHLOU Oct 07 '22 at 11:15
  • In which time zone? New Year doesn’t happen at the same instant in all time zones. – Ole V.V. Oct 08 '22 at 18:12

2 Answers2

2

Something like this should do the trick:

int year = 2022;

Instant instant = Year.of(year) // 2022
  .atDay(1)                     // 2022-01-01
  .atStartOfDay()               // 2022-01-01 00:00:00
  .toInstant(ZoneOffset.UTC);   // applied to timeline

There are more ways, but they essentially all go kinda that route. Have a look at the Javadoc and explore more: java.time package

Alexey R.
  • 8,057
  • 2
  • 11
  • 27
Zabuzard
  • 25,064
  • 8
  • 58
  • 82
1

Something like that should do the trick:

int year = 2022;
ZoneId zoneId = ZoneId.of("UTC");
Instant instant = ZonedDateTime.of(year, 1, 1, 0, 0, 0, 0, zoneId)
            .toInstant();

Creates ZonedDateTime at 00:00:00 on the january 1 in the target year, at required time zone and converts to instant.

Chaosfire
  • 4,818
  • 4
  • 8
  • 23