How to get and set specified time in java.time.Instant?
Asked Answered
U

4

35

I have two java.time.Instant objects

Instant dt1;
Instant dt2;

I want to get time (only hours and minutes without date) from dt2 and set it to dt1. What is the best way to to this? Using

dt2.get(ChronoField.HOUR_OF_DAY) 

throws java.time.temporal.UnsupportedTemporalTypeException

Unsparing answered 3/8, 2015 at 11:48 Comment(1)
Know that an instant is not specific to any one time zone or offset. You'll need to interpret the Instant in refernce to a time zone, in order to determine the hour of day.Diminution
A
61

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

Amylolysis answered 6/12, 2018 at 19:29 Comment(0)
S
8

Instant does not have any hour / minute. Please read the documentation of Instant class : https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html

If you use System Timezone to convert the Instant , you can use something like this :

LocalDateTime ldt1 = LocalDateTime.ofInstant(dt1, ZoneId.systemDefault());
        LocalDateTime ldt2 = LocalDateTime.ofInstant(dt2, ZoneId.systemDefault());

        ldt1 = ldt1
            .withHour(ldt2.getHour())
            .withMinute(ldt2.getMinute())
            .withSecond(ldt2.getSecond());

        dt1 = ldt1.atZone(ZoneId.systemDefault()).toInstant();
Spiers answered 3/8, 2015 at 15:31 Comment(0)
E
7

Convert first the Instant to LocalDateTime, and use UTC as its timezone, then you can get its hours.

import java.time.*
LocalDateTime.ofInstant(Instant.now(), ZoneOffset.UTC).getHour()
Engedus answered 23/3, 2017 at 10:14 Comment(2)
Instant.now() ?Thoroughwort
Googling for two days, finally found this one line and it works. (Java 11)Cognizant
M
0

While the upper answer is a good, I used it but in Kotlin. Thankyou @frido

while (startDate.isBefore(endDate)) {
        val year: Int = startDate.atZone(ZoneOffset.UTC).year
        val month: Int = startDate.atZone(ZoneOffset.UTC).monthValue
        val day: Int = startDate.atZone(ZoneOffset.UTC).dayOfMonth
        System.out.printf("%d.%d.%d\n", day, month, year)

        startDate = startDate.atZone(ZoneOffset.UTC).withDayOfMonth(
            day + 1
        ).toInstant()
    }
Mccutcheon answered 12/3, 2022 at 16:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.