java获取指定年(月)的第一天(秒)和最后一天(秒)

该代码片段展示了如何使用Java 8的LocalDate和LocalDateTime类来获取指定年份和月份的第一天及最后一天、第一秒及最后一秒。这些方法包括firstDateOfYear(), lastDateOfYear(), firstDateOfMonth(), lastDateOfMonth(), firstTimeOfYear(), lastTimeOfYear(), firstTimeOfMonth()和lastTimeOfMonth(),它们提供了计算日期和时间边界值的简洁方式。

直接上代码

public class LocalDateUtil {

    public static void main(String[] args) {
        System.out.println("firstDateOfYear: " + firstDateOfYear(2023));
        System.out.println("lastDateOfYear: " + lastDateOfYear(2023));
        System.out.println("firstDateOfMonth: " + firstDateOfMonth(2023, 2));
        System.out.println("lastDateOfMonth: " + lastDateOfMonth(2023, 2));
        System.out.println("firstTimeOfYear: " + firstTimeOfYear(2023));
        System.out.println("lastTimeOfYear: " + lastTimeOfYear(2023));
        System.out.println("firstTimeOfMonth: " + firstTimeOfMonth(2023, 2));
        System.out.println("lastTimeOfMonth: " + lastTimeOfMonth(2023, 2));
    }

    /**
     * 指定年份的第一天
     *
     * @param year 年份
     */
    public static LocalDate firstDateOfYear(int year) {
        return LocalDate.ofYearDay(year, 1);
    }

    /**
     * 指定年份的最后一天(用指定年份的第一天加1年,再减去1天)
     *
     * @param year
     * @return
     */
    public static LocalDate lastDateOfYear(int year) {
        return firstDateOfYear(year).plusYears(1).minusDays(1);
    }

    /**
     * 指定年月的第一天
     *
     * @param year  年份
     * @param month 月份
     */
    public static LocalDate firstDateOfMonth(int year, int month) {
        return LocalDate.of(year, month, 1);
    }

    /**
     * 指定年月的最后一天(用指定年月的第一天加1月,再减去1天)
     *
     * @param year  年份
     * @param month 月份
     */
    public static LocalDate lastDateOfMonth(int year, int month) {
        return firstDateOfMonth(year, month).plusMonths(1).minusDays(1);
    }

    /**
     * 指定年份的第一秒
     *
     * @param year
     * @return
     */
    public static LocalDateTime firstTimeOfYear(int year) {
        return LocalDateTime.of(LocalDate.ofYearDay(year, 1), LocalTime.MIN);
    }

    /**
     * 指定年份的最后一秒(用指定年份的第一秒加1年,再减去1秒)
     *
     * @param year
     * @return
     */
    public static LocalDateTime lastTimeOfYear(int year) {
        return firstTimeOfYear(year).plusYears(1).minusSeconds(1);
    }

    /**
     * 指定年月的第一秒
     *
     * @param year  年份
     * @param month 月份
     */
    public static LocalDateTime firstTimeOfMonth(int year, int month) {
        return LocalDateTime.of(LocalDate.of(year, month, 1), LocalTime.MIN);
    }

    /**
     * 指定年月的最后一秒(用指定年月的第一秒加1月,再减去1秒)
     *
     * @param year  年份
     * @param month 月份
     */
    public static LocalDateTime lastTimeOfMonth(int year, int month) {
        return firstTimeOfMonth(year, month).plusMonths(1).minusSeconds(1);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值