LocalDate

1、基本用法

LocalDate date = LocalDate.now();
LocalDate lastMonth = date.minusMonths(1); // 当前月份减1
LocalDate firstDay = lastMonth.with(TemporalAdjusters.firstDayOfMonth()); // 获取当前月的第一天
LocalDate lastDay = lastMonth.with(TemporalAdjusters.lastDayOfMonth()); // 获取当前月的最后一天
System.out.println("当前时间:" + date);
System.out.println("上月今天:" + lastMonth);
System.out.println();
System.out.println("上个月第一天:" + firstDay);
System.out.println("上个月最后一天:" + lastDay);
System.out.println();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
System.out.println("格式化日期:" + date.format(formatter));
System.out.println("年月日数字格式:" + lastDay.getYear());
System.out.println("年月日数字格式:" + lastDay.getMonthValue());
System.out.println("年月日数字格式:" + lastDay.getDayOfMonth());

在这里插入图片描述

2、获取上个月今天

获取上个月今天的时候,如果是这个月的最后一天比上个月多一天,会自动变成上个月的最后一天,如下所示:

LocalDate date = LocalDate.of(2022, 10, 31);
LocalDate lastMonth = date.minusMonths(1); // 当前月份减1

在这里插入图片描述

3、指定的年月日转LocalDate

LocalDate date = LocalDate.of(2022, 10, 9);

4、一年的第一天和最后一天

//年第一天
localDate.with(TemporalAdjusters.firstDayOfYear());
//年最后一天
localDate.with(TemporalAdjusters.lastDayOfYear();

5、获取是周几:

 public static void main(String[] args) {
        getDayOfWeek();
    }

    private static void getDayOfWeek() {

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate day1 = LocalDate.of(2022, 12, 5);
        LocalDate day2 = LocalDate.of(2022, 12, 11);

        while (day1.isBefore(day2) || day1.isEqual(day2)) {
            String attDate = day1.format(formatter);
            System.out.println(attDate + "\t:是周" + day1.getDayOfWeek().getValue());
            day1 = day1.plusDays(1);
        }
    }

运行结果:

2022-12-05	:是周1
2022-12-06	:是周2
2022-12-07	:是周3
2022-12-08	:是周4
2022-12-09	:是周5
2022-12-10	:是周6
2022-12-11	:是周7

6、LocalDate转String

LocalDate now = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

String now_str = now.format(formatter);
System.out.println(now_str);

7、String转LocalDate

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String now_str = "2023-07-11";
LocalDate parse = LocalDate.parse(now_str, formatter);
System.out.println(parse);	

8、两个LocalDate比较大小

// 使用 isBefore() 和 isAfter() 方法比较
boolean isBefore = date1.isBefore(date2);
boolean isAfter = date1.isAfter(date2);

if (isBefore) {
    System.out.println("date1 is before date2");
} else if (isAfter) {
    System.out.println("date1 is after date2");
} else {
    System.out.println("date1 and date2 are equal");
}   
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值