引入相关Package
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import com.example.base;
LocalDate 与 String 之间的互转
DateTimeFormatter fmt1 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate localDate = LocalDate.now();
String dateStr = localDate.format(fmt1);
System.out.println(dateStr);
String date1 = "2023-08-30";
LocalDate localDate1 = LocalDate.parse(date1, fmt1);
System.out.println(localDate1);
LocalTime 与 String 之间的互转
DateTimeFormatter fmt2 = DateTimeFormatter.ofPattern("HH:mm:ss");
LocalTime localTime1 = LocalTime.now();
LocalTime localTime2 = LocalTime.parse("12:30:30");
LocalTime localTime3 = LocalTime.parse("12:30:30", DateTimeFormatter.ofPattern("HH:mm:ss"));
System.out.println(localTime1.format(fmt2));
System.out.println(localTime2.format(fmt2));
System.out.println(localTime3.format(fmt2));
String localTime = "10:30:30";
LocalTime localTime4 = LocalTime.parse(localTime, fmt2);
System.out.println(localTime4);
LocalDateTime 与 String 之间的互转
DateTimeFormatter fmt3 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime ldt1 = LocalDateTime.parse("2019-12-07 21:20:06", fmt3);
LocalDateTime ldt2 = LocalDateTime.now();
System.out.println(fmt3.format(ldt1));
System.out.println(fmt3.format(ldt2));
String localDateTime_Str = "2023-12-07 21:20:06";
LocalDateTime ldt3 = LocalDateTime.parse(localDateTime_Str, fmt3);
System.out.println(ldt3);
Date与 LocalDate,LocalTime, LocalDateTime 互转
Date date = new Date();
ZoneId zoneId = ZoneId.systemDefault();
ZonedDateTime zonedDateTime = date.toInstant().atZone(zoneId);
LocalDateTime ldtime = zonedDateTime.toLocalDateTime();
//或者 LocalDateTime localDateTimex =
// LocalDateTime.ofInstant(date.toInstant(),zoneId);
LocalDate ld1 = zonedDateTime.toLocalDate();
LocalTime lt1 = zonedDateTime.toLocalTime();
System.out.println(ldtime);
System.out.println(ld1);
System.out.println(lt1);
LocalDate,LocalTime, LocalDateTime与Date互转
LocalDate lcd = LocalDate.now();
ZoneId zone = ZoneId.systemDefault();
Instant instant = lcd.atStartOfDay().atZone(zone).toInstant();
Date datefirst = Date.from(instant);
LocalTime localTime_1 = LocalTime.now();
LocalDate localDate_1 = LocalDate.now();
LocalDateTime localDateTime = LocalDateTime.of(localDate_1, localTime_1);
Instant inst = localDateTime.atZone(zone).toInstant();
Date dateSecond = Date.from(inst);
LocalDateTime localDateTime_1 = LocalDateTime.now();
ZoneId zoneId_1 = ZoneId.systemDefault();
Instant instant_1 = localDateTime_1.atZone(zoneId_1).toInstant();
Date dateThird = Date.from(instant_1);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(dateFormat.format(datefirst));
System.out.println(dateFormat.format(dateSecond));
System.out.println(dateFormat.format(dateThird));