localdateTime转date及localdatetime格式化日期格式转换为字符串
localdateTime转date及localdatetime格式化日期格式转换为字符串
import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.Date;public class LocalDateTimeToDate {public static void main(String[] args) {LocalDateTime localDateTime = LocalDateTime.now(); // 获取当前时间ZoneId zoneId = ZoneId.systemDefault(); // 获取系统默认时区ZonedDateTime zonedDateTime = localDateTime.atZone(zoneId); // 将 LocalDateTime 转换为 ZonedDateTimeDate date = Date.from(zonedDateTime.toInstant()); // 将 ZonedDateTime 的 Instant 转换为 DateSystem.out.println(date); // 打印 Date 对象 } }
如果你需要格式化你的LocalDateTime(例如:转换为字符串),你可以使用DateTimeFormatter。例如:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:MM:SS");
String formatted = localDateTime.format(formatter);