如何在java.time.Instant中获取和设置指定时间? [英] How to get and set specified time in java.time.Instant?

查看:1073
本文介绍了如何在java.time.Instant中获取和设置指定时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个java.time.Instant对象

I have two java.time.Instant objects

Instant dt1;
Instant dt2;

我想从dt2获取时间(只有小时和分钟,没有日期),并将其设置为dt1.最好的方法是什么?使用

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) 

引发java.time.temporal.UnsupportedTemporalTypeException

throws java.time.temporal.UnsupportedTemporalTypeException

推荐答案

您必须在某些时区解释Instant,以获取

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();

还有获取天,月和年(getX)的方法.

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();

还有更改天,月和年(withX)的方法,以及添加(plusX)或减去(minusX)时间或日期值的方法.

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.

这篇关于如何在java.time.Instant中获取和设置指定时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆