LocalDateTime 是 Java 8 引入的日期时间 API 的一部分,用于表示日期和时间,不包含时区信息。以下是一些常用的 LocalDateTime 相关方法:
now(): 获取当前的日期和时间。
of(int year, int month, int dayOfMonth, int hour, int minute, int second): 根据指定的日期和时间创建一个 LocalDateTime 实例。
getYear(): 获取年份。
getMonth(): 获取月份。
getDayOfMonth(): 获取月份中的天。
getHour(): 获取小时。
getMinute(): 获取分钟。
getSecond(): 获取秒。
plusDays(long daysToAdd): 添加天数。
plusHours(long hoursToAdd): 添加小时数。
plusMinutes(long minutesToAdd): 添加分钟数。
plusSeconds(long secondsToAdd): 添加秒数。
minusDays(long daysToSubtract): 减去天数。
minusHours(long hoursToSubtract): 减去小时数。
minusMinutes(long minutesToSubtract): 减去分钟数。
minusSeconds(long secondsToSubtract): 减去秒数。
isBefore(ChronoLocalDateTime other): 判断当前日期时间是否在指定的日期时间之前。
isAfter(ChronoLocalDateTime other): 判断当前日期时间是否在指定的日期时间之后。
format(DateTimeFormatter formatter): 使用指定的格式化器格式化日期时间。
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 specificTime = LocalDateTime.of(2023, 4, 1, 12, 30, 45);
System.out.println("指定日期时间: " + specificTime);
// 格式化日期时间
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formatted = now.format(formatter);
System.out.println("格式化后的日期时间: " + formatted);
// 增加时间
LocalDateTime plusOneHour = now.plusHours(1);
System.out.println("增加一小时后的日期时间: " + plusOneHour);
// 比较日期时间
if (now.isBefore(specificTime)) {
System.out.println("当前日期时间在指定日期时间之前");
} else {
System.out.println("当前日期时间在指定日期时间之后");
}
}
}