java String与localDateTime之间的转化

public class LocalDateTImeUtil {




    /**
     * LocalDateTime转String
     * @param localDateTime
     * @param format
     * @return
     */
    public static String format(LocalDateTime localDateTime,String format){
        DateTimeFormatter df = DateTimeFormatter.ofPattern(format);
        return df.format(localDateTime);
    }

    /**
     * String转LocalDateTime
     * @param str
     * @param format
     * @return
     */
    public static LocalDateTime parse(String str,String format){
        DateTimeFormatter df = DateTimeFormatter.ofPattern(format);
        return LocalDateTime.parse(str,df);
    }

    /**
     * 获取两个日期相差的天数
     * @param beginDateTime
     * @param endDateTime
     * @return
     */
    public static Integer getDaySub(LocalDateTime beginDateTime,LocalDateTime endDateTime){
        return endDateTime.getDayOfYear()-beginDateTime.getDayOfYear();
    }

    /**
     * 获取一天最早的时间
     * @param dateTime
     * @return
     */
    public static LocalDateTime getFirstDateTimeOfDay(LocalDateTime dateTime){
        return LocalDateTime.of(dateTime.toLocalDate(), LocalTime.MIN);
    }

    /**
     * 获取一天最晚的时间
     * @param dateTime
     * @return
     */
    public static LocalDateTime getLastDateTimeOfDay(LocalDateTime dateTime){
        return LocalDateTime.of(dateTime.toLocalDate(), LocalTime.MAX);
    }

    /**
     * 获取一个月内的最早一天
     * @param dateTime
     * @return
     */
    public static LocalDateTime getFirstDateTimeOfMonth(LocalDateTime dateTime){
        return LocalDateTime.of(LocalDate.from(dateTime.toLocalDate().with(TemporalAdjusters.firstDayOfMonth())), LocalTime.MIN);
    }

    /**
     * 获取一个月最后一天
     * @param dateTime
     * @return
     */
    public static LocalDateTime getLastDateTimeOfMonth(LocalDateTime dateTime){
        return LocalDateTime.of(LocalDate.from(dateTime.toLocalDate().with(TemporalAdjusters.lastDayOfMonth())), LocalTime.MAX);
    }

}

 

posted @ 2022-11-19 21:10  锐洋智能  阅读(1920)  评论(0编辑  收藏  举报