Java 8中 Date 获取时间所在 周一,月第一天,季度第一天,年第一天的方式

简述

Java 8 中 日期,时间API 完全重构。抛弃了原来非常复杂的 calendar. 还加入了线程安全的等更加友好的API。本文主要是记录分享 常用的 时间所在周,月,季度,年的 第一天获取方式。

周一

  /**
     * 获取时间戳的第一周
     * @param timestamp long
     * @return long
     */
    public static long getWeek1st(long timestamp) {
        return Instant.ofEpochMilli(timestamp).atZone(ZoneId.systemDefault()).with(DayOfWeek.MONDAY)
            .toInstant().toEpochMilli();
    }

月第一天

/**
     * 获取时间戳的月第一天
     * @param timestamp 时间戳
     * @return long
     */
    public static long getMonth1st(long timestamp) {
        return Instant.ofEpochMilli(timestamp).atZone(ZoneId.systemDefault())
            .with(TemporalAdjusters.firstDayOfMonth()).toInstant().toEpochMilli();
    }

季度第一天


    /**
     * 获取季度的一天
     * @param timestamp
     * @return
     */
    public static long quarterStart(long timestamp) {
        int month = Instant.ofEpochMilli(timestamp).atZone(ZoneId.systemDefault()).getMonth().getValue();
        final LocalDate date = Instant.ofEpochMilli(timestamp).atZone(ZoneId.systemDefault()).toLocalDate();
        int start = 0;
        // 第一季度
        if (month <= 3) {
            start = 1;
        } else if (month <= 6) {
            start = 4;
        } else if (month <= 9) {
            start = 7;
        } else {
            start = 10;
        }
        return date.plusMonths(start - month).with(TemporalAdjusters.firstDayOfMonth()).atStartOfDay()
            .atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
    }

当前年第一天


    /**
     * 当前年的第1天
     * @return
     */
    public static long getCurrentYear1st() {
        return LocalDate.now().atStartOfDay().with(TemporalAdjusters.firstDayOfYear()).atZone(ZoneId.systemDefault())
            .toInstant().toEpochMilli();
    }

总结

本文主要涉及的重点
时间戳转换为LocalDate,需要设置时区。

Instant.ofEpochMilli(timestamp).atZone(ZoneId.systemDefault())

LocalDate 获取 周,月,年的第一天使用with

TemporalAdjusters.firstDayOfYear()
DayOfWeek.MONDAY
TemporalAdjusters.firstDayOfMonth()

没有直接提供季度的方式,需要计算

如果文章有些许帮助,请关注,点赞吆。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章