java如何获得日期
获取当前日期
使用 java.util.Date 或 java.time.LocalDate:
// 使用 java.util.Date(旧版)
Date currentDate = new Date();
System.out.println(currentDate);
// 使用 java.time.LocalDate(Java 8+)
LocalDate today = LocalDate.now();
System.out.println(today); // 输出格式:2023-05-20
指定日期创建
通过 LocalDate.of() 或 SimpleDateFormat 解析字符串:

// 使用 LocalDate
LocalDate specificDate = LocalDate.of(2023, 5, 20);
// 使用 SimpleDateFormat(旧版)
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date parsedDate = sdf.parse("2023-05-20");
格式化日期输出
使用 DateTimeFormatter 或 SimpleDateFormat:
// 使用 DateTimeFormatter(Java 8+)
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
String formattedDate = today.format(formatter); // 输出:2023/05/20
// 使用 SimpleDateFormat(旧版)
SimpleDateFormat outputFormat = new SimpleDateFormat("dd-MM-yyyy");
String formatted = outputFormat.format(currentDate);
获取日期组成部分
通过 LocalDate 的方法提取年、月、日:

int year = today.getYear(); // 2023
int month = today.getMonthValue(); // 5
int day = today.getDayOfMonth(); // 20
日期加减操作
使用 plusDays() 或 minusMonths() 等方法:
LocalDate nextWeek = today.plusDays(7);
LocalDate prevMonth = today.minusMonths(1);
时区处理
结合 ZonedDateTime 处理时区:
ZonedDateTime zonedNow = ZonedDateTime.now(ZoneId.of("Asia/Shanghai"));
System.out.println(zonedNow); // 输出带时区的日期时间






