java Date裝成英文String后,無法再轉(zhuǎn)回Date的解決方案
這是同事遇到的一個問題。
代碼中的Date,放到頁面上的格式為“Fri Mar 21 09:20:38 CST 2014”(不顯示,只為傳遞到下一個controller),
再次提交表單時,Dto類的 private Date startTime; 沒有被set進值。
用本地程序做了一下實驗
public static void main(String[] args) { Date now = new Date(); System.out.println(now); String nowStr = now.toString(); DateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy"); Date parsedNow = null; try { parsedNow = format.parse(nowStr); System.out.println(parsedNow); } catch (ParseException e) { e.printStackTrace(); } }
程序執(zhí)行format.parse(nowStr)時報錯
Java.text.ParseException: Unparseable date: "Fri Mar 21 09:25:48 CST 2014"
at java.text.DateFormat.parse(DateFormat.java:337)
分析和查看源碼后得出結(jié)論,由系統(tǒng)所使用的語言導致的錯誤。
DateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
默認其實是
DateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", new Locale(System.getProperty("user.language")));
其中System.getProperty("user.language")由于系統(tǒng)是中文,所以為zh,應該是中文時區(qū)不支持此種format。
修改上面的代碼驗證此觀點
public static void main(String[] args) { Date now = new Date(); System.out.println(now); String nowStr = now.toString(); DateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", new Locale(System.getProperty("user.language"))); System.out.println(System.getProperty("user.language")); Date parsedNow = null; try { parsedNow = format.parse(nowStr); System.out.println(parsedNow); } catch (ParseException e) { format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH); try { System.out.println("new format by 'en'"); System.out.println(format.parse(nowStr)); } catch (ParseException e1) { e1.printStackTrace(); } } }
另一種解決方案是,在jsp頁面中,對日期格式進行一次轉(zhuǎn)換,如
<input type="hidden" name="data" value=' <fmt:formatDate value="${dto.date}" pattern="yyyy-MM-dd"/> '/>
以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持腳本之家!
相關文章
MyBatis-Plus實現(xiàn)字段自動填充功能的示例
本文主要介紹了MyBatis-Plus實現(xiàn)字段自動填充功能的示例,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-11-11POST方法給@RequestBody傳參數(shù)失敗的解決及原因分析
這篇文章主要介紹了POST方法給@RequestBody傳參數(shù)失敗的解決及原因分析,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-10-10MyBatis 中 ${}和 #{}的正確使用方法(千萬不要亂用)
這篇文章主要介紹了MyBatis 中 ${}和 #{}的正確使用方法,本文給大家提到了MyBatis 中 ${}和 #{}的區(qū)別,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-07-07