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()

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

如果文章有些許幫助,請關注,點贊吆。

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