繁体   English   中英

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

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

我有两个 java.time.Instant 对象

Instant dt1;
Instant dt2;

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

dt2.get(ChronoField.HOUR_OF_DAY) 

抛出 java.time.temporal.UnsupportedTemporalTypeException

您必须在某个时区解释 Instant 才能获得ZonedDateTime 当 Instant 测量从纪元1970-01-01T00:00:00Z的经过秒数和纳秒时,您应该使用UTC来获得与 Instant 打印的时间相同的时间。 ( Z ≙ 祖鲁时间 ≙ 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.atZone(ZoneOffset.UTC)
        .withHour(hour)
        .withMinute(minute)
        .withSecond(second)
        .withNano(nano)
        .toInstant();

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

要将时间设置为作为字符串使用的值: .with(LocalTime.parse("12:45:30"))

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

首先将Instant转换为LocalDateTime ,并使用 UTC 作为其时区,然后您可以获得它的小时数。

import java.time.*
LocalDateTime.ofInstant(Instant.now(), ZoneOffset.UTC).getHour()

虽然上面的答案很好,但我在 Kotlin 中使用了它。 谢谢@frido

while (startDate.isBefore(endDate)) {
        val year: Int = startDate.atZone(ZoneOffset.UTC).year
        val month: Int = startDate.atZone(ZoneOffset.UTC).monthValue
        val day: Int = startDate.atZone(ZoneOffset.UTC).dayOfMonth
        System.out.printf("%d.%d.%d\n", day, month, year)

        startDate = startDate.atZone(ZoneOffset.UTC).withDayOfMonth(
            day + 1
        ).toInstant()
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM