天天看點

Java 8中 Date 擷取時間所在 周一,月第一天,季度第一天,年第一天的方式

周一

/**
     * 擷取時間戳的第一周
     * @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()           

沒有直接提供季度的方式,需要計算