import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class LocalDateTimeExample {
public static void main(String[] args) {
// 获取当前日期和时间
LocalDateTime now = LocalDateTime.now();
System.out.println("当前日期和时间: " + now);
// 创建指定日期和时间的LocalDateTime对象
LocalDateTime specificDateTime = LocalDateTime.of(2023, 10, 5, 14, 30, 45);
System.out.println("指定的日期和时间: " + specificDateTime);
// 格式化日期和时间
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDateTime = now.format(formatter);
System.out.println("格式化后的日期和时间: " + formattedDateTime);
// 解析字符串为LocalDateTime对象
String dateTimeString = "2023-10-05 14:30:45";
LocalDateTime parsedDateTime = LocalDateTime.parse(dateTimeString, formatter);
System.out.println("解析后的日期和时间: " + parsedDateTime);
}
}
LocalDateTime.now() 方法获取当前的日期和时间。LocalDateTime.of(year, month, day, hour, minute, second) 方法创建一个指定日期和时间的 LocalDateTime 对象。DateTimeFormatter 类来定义日期和时间的格式,并通过 format() 方法将 LocalDateTime 对象格式化为字符串。LocalDateTime 对象:使用 parse() 方法将格式化的字符串解析回 LocalDateTime 对象。上一篇:java反射获取对象属性和值
下一篇:java中switch用法
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站