NIUCLOUD是一款SaaS管理后台框架多应用插件+云编译。上千名开发者、服务商正在积极拥抱开发者生态。欢迎开发者们免费入驻。一起助力发展! 广告
## Java LocalDate 详解 ### 什么是 LocalDate? `LocalDate` 是 Java 8 引入的新日期时间 API 中的一个类,用于表示**不带时区的日期**(年-月-日)。它是**不可变对象**,只包含日期信息,不包含时间和时区信息。 ### 主要特点: - **不可变性**:创建后不能被修改,保证线程安全 - **专注日期**:只处理年月日,不涉及时分秒 - **线程安全**:可以在多线程环境中安全使用 - **默认格式**:ISO-8601 格式(yyyy-MM-dd) ### 创建 LocalDate 的常用方法: ```java import java.time.LocalDate; // 1. 获取当前日期 LocalDate currentDate = LocalDate.now(); System.out.println("当前日期: " + currentDate); // 输出:2026-01-20 // 2. 创建指定日期 LocalDate specificDate = LocalDate.of(2023, 10, 5); System.out.println("指定日期: " + specificDate); // 输出:2023-10-05 // 3. 从字符串解析(默认格式 yyyy-MM-dd) LocalDate parsedDate = LocalDate.parse("2023-10-05"); System.out.println("解析的日期: " + parsedDate); // 输出:2023-10-05 ``` ### 生成 YYYY-MM-DD 格式的日期: ```java import java.time.LocalDate; import java.time.format.DateTimeFormatter; public class LocalDateExample { public static void main(String[] args) { // 获取当前日期 LocalDate currentDate = LocalDate.now(); // 方法1:直接使用默认格式(toString() 方法) String dateString1 = currentDate.toString(); System.out.println("方法1 - 默认格式: " + dateString1); // 输出:2026-01-20 // 方法2:使用 DateTimeFormatter 自定义格式 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); String dateString2 = currentDate.format(formatter); System.out.println("方法2 - 自定义格式: " + dateString2); // 输出:2026-01-20 // 方法3:创建指定日期并格式化 LocalDate specificDate = LocalDate.of(2023, 12, 25); String formattedDate = specificDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")); System.out.println("指定日期格式化: " + formattedDate); // 输出:2023-12-25 } } ``` ### 常用操作示例: ```java import java.time.LocalDate; import java.time.temporal.ChronoUnit; public class LocalDateOperations { public static void main(String[] args) { LocalDate date = LocalDate.of(2023, 10, 5); // 获取日期字段 int year = date.getYear(); // 2023 int month = date.getMonthValue(); // 10 int day = date.getDayOfMonth(); // 5 // 日期计算 LocalDate tomorrow = date.plusDays(1); // 加1天 LocalDate lastMonth = date.minusMonths(1); // 减1个月 // 日期比较 LocalDate otherDate = LocalDate.of(2023, 10, 10); boolean isBefore = date.isBefore(otherDate); // true boolean isAfter = date.isAfter(otherDate); // false // 计算两个日期之间的天数 long daysBetween = ChronoUnit.DAYS.between(date, otherDate); // 5 } } ``` ### 解决你的问题: 你遇到的错误 "Required type:LocalDate, Provided:String" 是因为你试图将字符串赋值给 LocalDate 类型的变量。正确的做法是: ```java // ❌ 错误:直接将字符串赋值给 LocalDate LocalDate date = "2023-10-05"; // 编译错误 // ✅ 正确:使用 parse 方法将字符串转换为 LocalDate LocalDate date = LocalDate.parse("2023-10-05"); // 或者使用自定义格式 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); LocalDate date = LocalDate.parse("2023-10-05", formatter); ``` LocalDate 是 Java 8 日期时间 API 中处理日期的首选类,相比旧的 Date 类更加安全、易用和功能丰富。