我有两个java.time.Instant对象
Instant dt1;
Instant dt2;
Run Code Online (Sandbox Code Playgroud)
我想从dt2获得时间(只有几小时和几分钟没有日期)并将其设置为dt1.最好的方法是什么?
dt2.get(ChronoField.HOUR_OF_DAY)
抛出java.time.temporal.UnsupportedTemporalTypeException
您必须在某个时区解释即时消息。当Instant度量从纪元经过的秒数和纳秒时,1970-01-01T00:00:00Z您应该使用它UTC来获取与Instant将会打印的时间相同的时间。
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();
Run Code Online (Sandbox Code Playgroud)
即时消息是一成不变的,因此您只能通过在给定时间更改后创建即时消息的副本来“设置”时间。
instant = instant.atZone(ZoneOffset.UTC)
.withHour(hour)
.withMinute(minute)
.withSecond(second)
.withNano(nano)
.toInstant();
Run Code Online (Sandbox Code Playgroud)
Instant没有任何小时/分钟.请阅读Instant类的文档:https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html
如果您使用系统时区转换Instant,您可以使用以下内容:
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();
Run Code Online (Sandbox Code Playgroud)
首先将 转换Instant为LocalDateTime,并使用 UTC 作为其时区,然后您可以获得它的小时数。
import java.time.*
LocalDateTime.ofInstant(Instant.now(), ZoneOffset.UTC).getHour()
Run Code Online (Sandbox Code Playgroud)