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