获取今天、今后、以前的年、月、日时间,日期差值

使用java.time.LocalDate类来表示一个日期。
LocalDate.now()方法获取当前日期,
1.要获取昨天的日期:
可以使用LocalDate类的minusDays()方法来减去一天。

private static void dateTest() throws Exception {
    LocalDate today = LocalDate.now();
    LocalDate yesterday = today.minusDays(1);//可以是不同数值,如值为2是前天
    System.out.println("Yesterday's date: " + yesterday.toString());
    //打印结果:Yesterday's date: 2024-07-15
}

   2.获取年份
LocalDate today = LocalDate.now(); // 获取今天的日期
int year = today.getYear(); // 获取年份
System.out.println("今天的年份是: " + year);

 3.获取以前的月份

LocalDate today = LocalDate.now(); // 获取今天的日期
YearMonth yearMonth = YearMonth.of(today.getYear(), today.getMonthValue());
YearMonth yearMonth2 = yearMonth.minusMonths(4);

System.out.println("新的month是: " + yearMonth2);

4.日期差值

String myDateStr="2024-06-20";
 String[] dateStr = myDateStr.split(HdConstant.CHAR_MIDDLE_LINE);

  LocalDe myDate = LocalDate.of(Integer.parseInt(dateStr[0]), Integer.parseInt(dateStr[1]),Integer.parseInt(dateStr[2]));
            // 两个日期, 计算日期差值:myDate-LocalDate.now(),
            long daysDiff = ChronoUnit.DAYS.between(LocalDate.now(), myDate);

5.综合实例:

 private static void yearTest() throws Exception {
        LocalDate today = LocalDate.now(); // 获取今天的日期
        int year = today.getYear(); // 获取年份
        System.out.println("今天的年份是: " + year);
    }

private static void yearMonthTest() throws Exception {
    LocalDate today = LocalDate.now(); // 获取今天的日期
    System.out.println("today是: " + today);
    YearMonth yearMonth = YearMonth.of(today.getYear(), today.getMonthValue());
    YearMonth yearMonth1 = yearMonth.minusYears(4);//minus 4 year
    System.out.println("1减year是: " + yearMonth1);
    YearMonth yearMonth2 = yearMonth.plusYears(4);//add 4 year
    System.out.println("2加year是: " + yearMonth2);
    YearMonth yearMonth3 = yearMonth.minusMonths(4);//以前的月份
    System.out.println("3加month是: " + yearMonth3);
    YearMonth yearMonth4 = yearMonth.plusMonths(4);//add月份
    System.out.println("4减month是: " + yearMonth4);

    //执行结果

today是: 2024-07-31
1减year是: 2020-07
2加year是: 2028-07
3加month是: 2024-03
4减month是: 2024-11

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值