Java中日期YearMonth类的常用方法实现

import java.time.YearMonth;

public class TestClass {
    public static void main(String[] args) {
        // 获取当前年月
        YearMonth current = YearMonth.now();
        System.out.println("当前年月:" + current);

        // 获取指定年月
        YearMonth specified = YearMonth.of(2022, 2);
        System.out.println("指定年月:" + specified);

        // 获取当前年月的天数
        int days = current.lengthOfMonth();
        System.out.println("当前年月的天数:" + days);

        // 获取指定年月的天数
        int days2 = specified.lengthOfMonth();
        System.out.println("指定年月的天数:" + days2);

        // 增加或减少年份
        YearMonth addYear = current.plusYears(1);
        YearMonth minusYear = current.minusYears(1);
        System.out.println("当前年月增加1年:" + addYear);
        System.out.println("当前年月减少1年:" + minusYear);

        // 增加或减少月份
        YearMonth addMonth = current.plusMonths(3);
        YearMonth minusMonth = current.minusMonths(3);
        System.out.println("当前年月增加3个月:" + addMonth);
        System.out.println("当前年月减少3个月:" + minusMonth);
        
        //获取指定月份的最后一天
        String zuihouyitian= YearMonth.parse("2023-09").atEndOfMonth().toString()
        
        LocalDate currentDate = LocalDate.now();
        
        LocalDate firstDayOfMonth = currentDate.withDayOfMonth(1);
        System.out.println("月份的第一天:" + firstDayOfMonth);
        int dayOfMonth = LocalDate.now().getDayOfMonth();
        System.out.println("月份已过天数:" + dayOfMonth);
    
        LocalDate dueDate = LocalDate.parse("2025-08-17");
      // 到期日期增加一天
        System.out.println(dueDate + "增加一天:" + dueDate.plusDays(1));
        // 到期日期后退一天
        System.out.println(dueDate + "减一天:" + dueDate.plusDays(-1));
        // 到期日期增加一个月
        System.out.println(dueDate + "增加一个月:" + dueDate.plusMonths(1));
        // 到期日期增加一周
        System.out.println(dueDate + "增加一周:" + dueDate.plusWeeks(1));
        // 到期日期增加一个月,并指定15日
        System.out.println(dueDate + "增加一个月,日期为15日:" + dueDate.plusMonths(1).withDayOfMonth(15));



    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值