Create first Instant of year 2022

86 Views Asked by At

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?

2

There are 2 best solutions below

0
Zabuzard On

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

0
Chaosfire On

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.