java生成指定时间,如何在java.time.Instant中获取和设置指定时间?

该博客介绍了如何从一个Java `Instant` 对象中获取小时和分钟,并将其设置到另一个 `Instant` 对象上。首先,需要将 `Instant` 转换为 `ZonedDateTime`,使用 `ZoneOffset.UTC` 获取时间,然后通过 `withHour` 和 `withMinute` 方法设置新的时间,并创建一个新的 `Instant` 实例。
摘要由CSDN通过智能技术生成

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

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值