1、報錯
轉(zhuǎn)換格式:SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
報錯:
java.text.ParseException: Unparseable date: "2020/1/12"
at java.text.DateFormat.parse(DateFormat.java:366)
at com.hxjs.website.modules.epanalysis.controller.ScehduledThread.run(ScehduledThread.java:53)
at com.hxjs.website.modules.sys.controller.SysLoginController$1.run(SysLoginController.java:106)
at java.util.TimerThread.mainLoop(Timer.java:555)
at java.util.TimerThread.run(Timer.java:505)
2、分析原因
SimpleDateFormat simpleFormat = new SimpleDateFormat(“yyyy-MM-dd hh:mm:ss”);
我所使用的與實際要轉(zhuǎn)換的不一致,導(dǎo)致報錯
3、解決
在轉(zhuǎn)換的時候必須保持 轉(zhuǎn)換字符串和轉(zhuǎn)換類型格式一致
提供一個代碼片段(只是簡單做了一下判斷,只能滿足幾種日期轉(zhuǎn)換(寫的不是很好,有待優(yōu)化))文章來源:http://www.zghlxwxcb.cn/news/detail-626738.html
/**
* 日期類型轉(zhuǎn)換
* @param date
* @return
* @throws ParseException
*/
private Date dateCl(String date) throws ParseException {
SimpleDateFormat simpleDateFormat=null;
if (date.contains("-") && date.contains(":")){
if (Objects.equals(stringCount(date,":"),2)){
simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
return simpleDateFormat.parse(date);
}else if (Objects.equals(stringCount(date,":"),1)){
simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd hh:mm");
return simpleDateFormat.parse(date);
}
}else if (date.contains("/") && date.contains(":")){
if (Objects.equals(stringCount(date,":"),2)){
simpleDateFormat=new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
return simpleDateFormat.parse(date);
}else if (Objects.equals(stringCount(date,":"),1)){
simpleDateFormat=new SimpleDateFormat("yyyy/MM/dd hh:mm");
return simpleDateFormat.parse(date);
}
}else if (date.contains("/") && !date.contains(":")){
simpleDateFormat=new SimpleDateFormat("yyyy/MM/dd");
return simpleDateFormat.parse(date);
}else if (date.contains("-") && !date.contains(":")){
simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
return simpleDateFormat.parse(date);
}
return null;
}
/**
* 獲取字符串出現(xiàn)的次數(shù)
* @param data
* @param s
* @return
*/
private int stringCount(String data,String s){
String str = data;
String searchChar = s;
int count = 0;
int origialLength = str.length();
str = str.replace(searchChar, "");
int newLength = str.length();
count = origialLength - newLength;
return count;
}
4、補(bǔ)充
1、使用SimpleDateFormat對時間進(jìn)行格式化,但SimpleDateFormat是線程不安全的,推薦使用LocalDateTime
參考此篇博客文章來源地址http://www.zghlxwxcb.cn/news/detail-626738.html
到了這里,關(guān)于SimpleDateFormat :{ ParseException: Unparseable date} 問題原因以及解決方法的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!