我有两个java.time.Instant对象
Instant dt1;
Instant dt2;我想从dt2获取时间(只有小时和分钟,没有日期),并将其设置为dt1。最好的方法是什么呢?使用
dt2.get(ChronoField.HOUR_OF_DAY) 抛出java.time.temporal.UnsupportedTemporalTypeException
发布于 2018-12-07 03:29:15
你必须在某个时区解释Instant才能获得ZonedDateTime。由于Instant从纪元1970-01-01T00:00:00Z开始测量经过的秒和纳秒,您应该使用UTC来获得与Instant打印的时间相同的时间。(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)的方法。
设置时间
instant是不可变的,因此您只能通过创建具有给定时间更改的instant的副本来“设置”时间。
instant = instant.atZone(ZoneOffset.UTC)
.withHour(hour)
.withMinute(minute)
.withSecond(second)
.withNano(nano)
.toInstant();还有更改日、月和年(withX)的方法,以及添加(plusX)或减去(minusX)时间或日期值的方法。
要将时间设置为以字符串形式给出的值,请使用:.with(LocalTime.parse("12:45:30"))
发布于 2015-08-03 23:31:13
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();发布于 2017-03-23 18:14:26
首先将Instant转换为LocalDateTime,并使用UTC作为它的时区,然后就可以得到它的小时数。
import java.time.*
LocalDateTime.ofInstant(Instant.now(), ZoneOffset.UTC).getHour()https://stackoverflow.com/questions/31786450
复制相似问题