可以使用 Java 8 的 DateTimeFormatter
類來判斷日期字符串是否符合指定格式。具體代碼如下:
String dateString = "2023-04-18 10:30:45";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
try {
LocalDateTime dateTime = LocalDateTime.parse(dateString, formatter);
System.out.println("日期格式正確:" + dateTime);
} catch (DateTimeParseException e) {
System.out.println("日期格式不正確:" + dateString);
}
如果你不想通過捕獲異常的方式來判斷日期字符串是否符合指定格式,也可以使用 DateTimeFormatter
類中的 parseUnresolved()
方法來進(jìn)行解析。具體代碼如下:
String dateString = "2023-04-18 10:30:45";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
TemporalAccessor temporal = formatter.parseUnresolved(dateString, new ParsePosition(0));
if (temporal == null) {
System.out.println("日期格式不正確:" + dateString);
} else {
LocalDateTime dateTime = LocalDateTime.from(temporal);
System.out.println("日期格式正確:" + dateTime);
}
以上代碼中,使用 parseUnresolved()
方法對(duì)日期字符串進(jìn)行解析,返回一個(gè) TemporalAccessor
對(duì)象,表示解析后的時(shí)間信息。如果解析失敗,則 temporal
為 null
,否則,將 temporal
轉(zhuǎn)換成 LocalDateTime
對(duì)象即可。文章來源:http://www.zghlxwxcb.cn/news/detail-599909.html
需要注意的是,如果日期字符串與指定格式不匹配,parseUnresolved()
方法不會(huì)拋出異常,而是返回 null
。因此,需要手動(dòng)判斷返回值是否為 null
來確定日期字符串是否符合指定格式。文章來源地址http://www.zghlxwxcb.cn/news/detail-599909.html
到了這里,關(guān)于Java 8 判斷日期字符串是否符合指定格式的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!