java 字符串如何直接轉LocalDateTime?


1.情景展示

  在實際開發過程中,可能會遇到將前端傳的日期格式轉成LocalDateTime插入到數據庫的情況,如何將日期轉成LocalDateTime呢?

2.原因分析

  在Java8中,日期類不同於以前版本的java.util.Date工具類,Date類可以存日期也可以存時間,還能存日期+時間,統統都能塞進去;

  但java8中將日期與時間拆分開來,日期類使用LocalDate,時間類使用LocalTime,日期+時間,使用LocalDateTime;

  如果我們見日期塞進LocalDateTime就會報錯:

DateUtil.toLocalDateTime("2021年07月28日", "yyyy年MM月dd日");  

  這個錯誤的意思就是:日期格式無法轉成日期+時間格式。

3.解決方案

  既然,LocalDateTime需要時間,而我們又只有日期的情況下,那就只能自己偽造時間啦。

  方式一:手動拼接時間00:00:00

/*
 * 字符串拼接轉日期
 * @date: 2020年08月20日 0020 15:51
 * @param: date
 * @param: format
 * @return: java.time.LocalDateTime
 */
public static LocalDateTime toLocalDateTime(String dateTime, String format) {
    if (StringUtils.isEmpty(dateTime)) {
        return null;
    }
    if (StringUtils.isEmpty(format)) {
        format = "yyyy-MM-dd HH:mm:ss";
    }

    DateTimeFormatter df = DateTimeFormatter.ofPattern(format);
    LocalDateTime ldt = LocalDateTime.parse(dateTime,df);
    return ldt;
}

  調用

String dateStr = "2021年07月28日";
dateStr += " 00:00:00";

LocalDateTime dateTime = DateUtil.toLocalDateTime(dateStr, "yyyy年MM月dd日 HH:mm:ss");
System.out.println(dateTime);

  執行結果:  

  2021-07-28T00:00 

  方式二:DateTimeFormatter設置可選匹配項默認值

/*
 * 日期字符串按指定格式轉LocalDateTime
 * @attention:
 * @date: 2021/7/28 15:05
 * @param: dateStr
 * @param: format
 * @return: java.time.LocalDateTime
 */
@NotNull
public static LocalDateTime toLocalDateTime(String dateStr, @NotNull String format) {
    DateTimeFormatter formatter;
    if (StringUtils.isEmpty(format)) {
        format = "yyyy-MM-dd";
    }
    
    if (format.length() > 11) {// 包含時間
        formatter = DateTimeFormatter.ofPattern(format);
    } else {// 只有日期
        formatter = new DateTimeFormatterBuilder()
                .appendPattern(format + "[['T'HH][:mm][:ss]]")
                .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
                .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
                .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
                .parseDefaulting(ChronoField.MILLI_OF_SECOND, 0)
                .toFormatter();
    }

    return LocalDateTime.parse(dateStr, formatter);
}

  調用  

System.out.println(DateUtils.toLocalDateTime("2021年07月28日", "yyyy年MM月dd日"));

  執行結果:  

  2021-07-28T00:00

寫在最后

  哪位大佬如若發現文章存在紕漏之處或需要補充更多內容,歡迎留言!!!

 相關推薦:

 


免責聲明!

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



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