如何在java中把Instant转换为LocalDate

561 阅读1分钟

在这篇文章中,我们将看到如何在java中把Instant转换为LocalDate。

使用ofInstant方法 [ Java 9+]

Java 9在LocalDate 类中引入了静态方法ofInstant() 方法。它将InstantZoneId 作为输入,并返回LocalDate 对象。

public static LocalDate ofInstant(Instant instant,ZoneId zone)

让我们借助于例子来看看。

package org.arpit.java2blog;

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;

public class InstantToLocalDate {

    public static void main(String[] args) {

        // Create Instant object
        Instant instant = Instant.parse("2022-01-23T00:00:00Z");

        // Get ZoneID
        ZoneId zone = ZoneId.of("Europe/London");

        // Convert Instant to LocalDate using ofInstant method
        LocalDate localDate = LocalDate.ofInstant(instant, zone);

        // Print LocalDate
        System.out.println("LocalDate Obj: "+localDate);
    }
}

输出。

LocalDate Obj: 2022-01-23

使用ZoneDateTime的toLocalDate()[Java 8]

  • 获取你想转换为LocalDate的Instant 对象。
  • 在Location的基础上创建ZoneId 实例。
  • ZoneId 传递给atZone() 方法,得到ZoneDateTime
  • ZoneDateTime 对象调用toLocalDate() ,得到LocalDate
package org.arpit.java2blog;

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class InstantToLocalDate {

    public static void main(String[] args) {

        // Create Instant object
        Instant instant = Instant.parse("2022-01-23T00:00:00Z");

        // Get ZoneID
        ZoneId zoneId = ZoneId.of("Europe/London");

        // Get zoneDateTime using Instant's atZone() method
        ZonedDateTime zonedDateTime = instant.atZone(zoneId);

        // Convert Instant to LocalDate using toLocalDate method
        LocalDate localDate = zonedDateTime.toLocalDate();

        // Print LocalDate
        System.out.println("LocalDate Obj: "+localDate);
    }
}

输出。

LocalDate Obj: 2022-01-23

以上就是关于如何在java中把Instant转换成LocalDate的全部内容。