java輕松玩轉localdatetime


廢話不多說,直接上代碼

 //時間戳轉LocalDateTime
    public static LocalDateTime getLocalDateTime(long timestamp) {
        Instant instant = Instant.ofEpochMilli(timestamp);
        ZoneId zone = ZoneId.systemDefault();
        return LocalDateTime.ofInstant(instant, zone);
    }

    //獲取當月最后一天
    public static LocalDateTime getLastDayOfCurrentMonth(LocalDateTime localDateTime) {
        return localDateTime.with(TemporalAdjusters.lastDayOfMonth()).toLocalDate().atStartOfDay();
    }

    //獲取當月第一天
    public static LocalDateTime getFirstDayOfCurrentMonth(LocalDateTime localDateTime) {
        return localDateTime.with(TemporalAdjusters.firstDayOfMonth()).toLocalDate().atStartOfDay();
    }

    //凌晨
    public static LocalDateTime getMorning(LocalDateTime localDateTime) {
        ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime.toLocalDate().atStartOfDay(), ZoneId.systemDefault());
        return zonedDateTime.toLocalDateTime();
    }

    //返回月份之間的月份
    public static List<String> getMonthBetween(LocalDateTime localDateTime, int minMonth, int maxMonth) {
        LocalDateTime min = localDateTime.withMonth(minMonth).with(TemporalAdjusters.firstDayOfMonth());
        LocalDateTime max = localDateTime.withMonth(maxMonth).with(TemporalAdjusters.lastDayOfMonth());
        List<String> result = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
        while (min.isBefore(max)) {
            result.add(min.format(formatter));
            min = min.plusMonths(1);
        }
        return result;
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM