如何在 Java 中將 Date 物件轉換為 LocalDate 物件?
在 Java 中將Date 物件轉換為 LocalDate 物件 −
使用 toInstant() 方法將獲取的 date 物件轉換為 Instant 物件。
Instant instant = date.toInstant();
使用 Instant 類中的 atZone() 方法建立 ZonedDateTime 物件。
ZonedDateTime zone = instant.atZone(ZoneId.systemDefault());
最後,使用 toLocalDate() 方法將 ZonedDateTime 物件轉換為 LocalDate 物件。
LocalDate givenDate = zone.toLocalDate();
示例
以下示例從使用者處以字串格式接收姓名和出生日期,然後將其轉換為LocalDate 物件並打印出來。
import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.Instant; import java.time.LocalDate; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.Date; import java.util.Scanner; public class DateToLocalDate { public static void main(String args[]) throws ParseException { //Reading name and date of birth from the user Scanner sc = new Scanner(System.in); System.out.println("Enter your name: "); String name = sc.next(); System.out.println("Enter your date of birth (dd-MM-yyyy): "); String dob = sc.next(); //Converting String to Date SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); Date date = formatter.parse(dob); //Converting obtained Date object to LocalDate object Instant instant = date.toInstant(); ZonedDateTime zone = instant.atZone(ZoneId.systemDefault()); LocalDate localDate = zone.toLocalDate(); System.out.println("Local format of the given date of birth String: "+localDate); } }
輸出
Enter your name: Krishna Enter your date of birth (dd-MM-yyyy): 26-09-1989 Local format of the given date of birth String: 1989-09-26
廣告