You have to interpret the Instant at some time zone to get ZonedDateTime
. As an Instant measures the ellapsed seconds and nano seconds from epoch 1970-01-01T00:00:00Z
you should use UTC
to get the same time as the Instant would print. (Z
≙ Zulu Time ≙ UTC
)
Getting the time
Instant instant;
// get overall time
LocalTime time = instant.atZone(ZoneOffset.UTC).toLocalTime();
// get hour
int hour = instant.atZone(ZoneOffset.UTC).getHour();
// get minute
int minute = instant.atZone(ZoneOffset.UTC).getMinute();
// get second
int second = instant.atZone(ZoneOffset.UTC).getSecond();
// get nano
int nano = instant.atZone(ZoneOffset.UTC).getNano();
There are also methods to get days, month and year (getX
).
Setting the time
Instants are immutable so you can only "set" the time by creating a copy of your instant with the given time change.
instant = instant.atZone(ZoneOffset.UTC)
.withHour(hour)
.withMinute(minute)
.withSecond(second)
.withNano(nano)
.toInstant();
There are also methods to alter days, month and year (withX
) as well as methods to add (plusX
) or subtract (minusX
) time or date values.
To set the time to a value given as a string use: .with(LocalTime.parse("12:45:30"))