LocalDate:日期类
LocalTime:时间类
LocalDateTime:日期时间类
相关操作
创建时间
private static void dateTimeAndFormat() {
// 当前日期时间
LocalDate date1 = LocalDate.now();
// 指定日期时间
LocalDate date2 = LocalDate.of(2025, 6, 6);
System.out.println(date1);
System.out.println(date2);
// 日期格式化
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
System.out.println(date1.format(fmt));
System.out.println(date2.format(DateTimeFormatter.ofPattern("yyyy_MM_dd")));
}
日期格式化
private static void format() {
// 日期格式化
// 默认:yyyy-MM-dd
LocalDate date = LocalDate.now();
System.out.printf("Date format %s\n", date);
// 时间 不想要毫秒使用.withNano(0)
// 默认:HH:mm:ss
LocalTime time = LocalTime.now();
System.out.printf("Time format %s\n", time);
// 自定义格式
LocalDateTime dateTime = LocalDateTime.now();
String dateTimeStr = dateTime.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss"));
System.out.printf("DateTime format %s\n", dateTimeStr);
}
将 String 转为日期与计算日期
private static void dateCalculate() {
// 将string类型的时间转换成LocalDate 或者 LocalTime 或者 LocalDateTime
String dateStr = "2025年05月20日";
// 转换为LocalDate
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
LocalDate date = LocalDate.parse(dateStr, fmt);
// 20天前
LocalDate dateAgo = date.plusDays(-20);
System.out.println(date.format(fmt) + " 20天前是 " + dateAgo.format(fmt));
// 计算两个日期间隔的年月日 是以年为单位
LocalDate date1 = LocalDate.parse("2020-05-20");
LocalDate date2 = LocalDate.parse("2021-09-09");
Period period = Period.between(date1, date2);
System.out.println("date1到date2间隔" + period.getYears() + "年" + period.getMonths() + "月" + period.getDays() + "日");
// 计算两个日期间隔多少天
long day = date2.toEpochDay() - date1.toEpochDay();
System.out.println("间隔" + (day + 123) + "天");
}
获取某一天
private static void getDay(){
LocalDate date = LocalDate.now();
// 获取当月第一天
LocalDate firstDay = date.with(TemporalAdjusters.firstDayOfMonth());
System.out.println(firstDay);
// 获取当月最后一天
LocalDate lastDay = date.with(TemporalAdjusters.lastDayOfMonth());
System.out.println(lastDay);
// 获取次月第一天 就是当月最后一天加1
LocalDate nextMonthFirstDay = date.with(TemporalAdjusters.firstDayOfNextMonth());
System.out.println(nextMonthFirstDay);
// 当年第一天
LocalDate firstDayYear = date.with(TemporalAdjusters.firstDayOfYear());
System.out.println(firstDayYear);
// 当年最后一天
LocalDate lastDayYear = date.with(TemporalAdjusters.lastDayOfYear());
System.out.println(lastDayYear);
// 当年最后一个周日
LocalDate lastSundayYear = lastDayYear.with(TemporalAdjusters.lastInMonth(DayOfWeek.SUNDAY));
System.out.println(lastSundayYear);
}
标签:format,System,date,日期,使用,println,LocalDate,Java8,out
From: https://blog.csdn.net/qq_64353233/article/details/142265869