String装换为Date
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
String dateString = "2023-08-09 14:57:14.0";
String pattern = "yyyy-MM-dd HH:mm:ss.S"; // Define the pattern that matches your date string
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
try {
Date date = dateFormat.parse(dateString);
System.out.println("Parsed Date: " + date);
} catch (ParseException e) {
e.printStackTrace(); // Handle parsing exception
}
}
}
String转换为LocalDatetime
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class test01 {
public static void main(String[] args) {
String timeString = "2023-08-09 14:57:14.0";//2023-08-09 14:57:14.0 最后的".0"一定不能少
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S");
LocalDateTime dateTime = LocalDateTime.parse(timeString, formatter);
System.out.println(dateTime);
}
}
Date 转换为 LocalDateTime
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
public class Main {
public static void main(String[] args) {
Date date = new Date();
Instant instant = date.toInstant();
LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
System.out.println("Date: " + date);
System.out.println("LocalDateTime: " + localDateTime);
}
}
LocalDateTime 转换为 Date
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
public class Main {
public static void main(String[] args) {
LocalDateTime localDateTime = LocalDateTime.now();
Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
System.out.println("LocalDateTime: " + localDateTime);
System.out.println("Date: " + date);
}
}