如何在Java中将Date对象转换为LocalDate对象?
在Java中将Date对象转换为LocalDate对象-
使用toInstant()方法将获取的日期对象转换为Instant对象。
Instant instant = date.toInstant();
使用Instant类的 atZone()方法创建ZonedDateTime对象。
ZonedDateTime zone = instant.atZone(ZoneId.systemDefault());
最后,使用toLocalDate()方法将ZonedDateTime 对象转换为LocalDate对象。
LocalDate givenDate = zone.toLocalDate();
示例
以下示例从用户接受String格式的名称和生日,并将其转换为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 {
//从用户读取姓名和出生日期
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();
//将字符串转换为日期
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
Date date = formatter.parse(dob);
//将获取的Date对象转换为LocalDate对象
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