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
According to the Java documentation, an instant is a measured timestamp from the Java epoch of 1970-01-01T00:00:00Z. Java 8 comes with a handy class called Instant to represent a specific instantaneous point on the timeline. Typically, we can use this class to record event timestamps in our applications.
No, an Instant is not at local time. An Instant by definition is in UTC.
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
)
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
).
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"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With