日期相关的API

192 阅读1分钟

minus(),plus()可以对当前日期进行加减操作。

between()可以计算两个日期之间的差值。

with()配合TemporalAdjusters可以获取特定日期,如本月第一天、本年程序员日等。

with()也可以接受自定义的调整逻辑。

query()可以根据某个判断逻辑查询日期是否满足条件。

private static void test() {
    System.out.println("//测试操作日期");
    System.out.println(LocalDate.now()
            .minus(Period.ofDays(1))
            .plus(1, ChronoUnit.DAYS)
            .minusMonths(1)
            .plus(Period.ofMonths(1)));

    System.out.println("//计算日期差");
    LocalDate today = LocalDate.of(2019, 12, 12);
    LocalDate specifyDate = LocalDate.of(2019, 10, 1);
    System.out.println(Period.between(specifyDate, today).getDays());
    System.out.println(Period.between(specifyDate, today));
    System.out.println(ChronoUnit.DAYS.between(specifyDate, today));


    System.out.println("//本月的第一天");
    System.out.println(LocalDate.now().with(TemporalAdjusters.firstDayOfMonth()));

    System.out.println("//今年的程序员日");
    System.out.println(LocalDate.now().with(TemporalAdjusters.firstDayOfYear()).plusDays(255));

    System.out.println("//今天之前的一个周六");
    System.out.println(LocalDate.now().with(TemporalAdjusters.previous(DayOfWeek.SATURDAY)));

    System.out.println("//本月最后一个工作日");
    System.out.println(LocalDate.now().with(TemporalAdjusters.lastInMonth(DayOfWeek.FRIDAY)));

    System.out.println("//自定义逻辑");
    System.out.println(LocalDate.now().with(temporal -> temporal.plus(ThreadLocalRandom.current().nextInt(100), ChronoUnit.DAYS)));

    System.out.println("//查询是否是今天要举办生日");
    System.out.println(LocalDate.now().query(CommonMistakesApplication::isFamilyBirthday));

}

学习:Java 业务开发常见错误 100 例学习笔记