Java String 转 LocalDateTime

String字符串正常情况:例如:2022-11-23 12:13:08

/**
* 常用的时间格式
*/
public static final String format_DateTime = "yyyy-MM-dd HH:mm:ss";
DateTimeFormatter df = DateTimeFormatter.ofPattern(format_DateTime);
LocalDateTime localDateTime = LocalDateTime.parse("2022-11-23 12:13:08", df);

String字符串非正常情况下,例如:2022-8-2 9:30:2

    /**
     * string 转换为LocalDateTime
     */
    public static LocalDateTime stringToLocalTime(String str){
        /**
         * 处理一下str
         * 月,日,时分秒
         * 有可能有时候一位数
         * 这时候需要在前面加个0
         */
        String[] s = str.split(" ");
        String yearMonthDay = s[0];
        String[] ymdArray = yearMonthDay.split("-");
        // 年
        String year = ymdArray[0];
        // 月
        String month = ymdArray[1];
        // 日
        String day = ymdArray[2];
        String hourMinuteSecond = s[1];
        String[] hmsArray = hourMinuteSecond.split(":");
        // 时
        String hour = hmsArray[0];
        // 分
        String minute = hmsArray[1];
        // 秒
        String second = hmsArray[2];
        if (month.length() == 1){
            month = "0" + month;
        }
        if (day.length() == 1){
            day = "0" + day;
        }
        if (hour.length() == 1){
            hour = "0" + hour;
        }
        if (minute.length() == 1){
            minute = "0" + minute;
        }
        if (second.length() == 1){
            second = "0" + second;
        }
        String str1 = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
        DateTimeFormatter df = DateTimeFormatter.ofPattern(format_DateTime);
        LocalDateTime localDateTime = LocalDateTime.parse(str1, df);
        return localDateTime;
    }

这样就能确保格式化的时候不会出错了

posted @ 2022-11-24 16:00  合起来的彳亍  阅读(5468)  评论(0编辑  收藏  举报