Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 571
kostepanych Avatar asked Aug 03 '15 11:08

kostepanych


People also ask

What is instant time in Java?

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.

Is instant in UTC Java?

No, an Instant is not at local time. An Instant by definition is in UTC.


1 Answers

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

like image 152
frido Avatar answered Nov 01 '22 09:11

frido