當(dāng)前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
SpringMVC 中设置日期字符串转换格式
生活随笔
收集整理的這篇文章主要介紹了
SpringMVC 中设置日期字符串转换格式
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
2019獨角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>
? ? 在使用SpringMVC的項目中經(jīng)常遇到?controller 參數(shù)中接收Date類型的數(shù)據(jù),但是頁面?zhèn)鬟^來的參數(shù)又是日期字符串,會出現(xiàn)轉(zhuǎn)換異常。
由于項目需要支持兩種日期格式所以從寫了一個日期轉(zhuǎn)換器。網(wǎng)友可以根據(jù)自己需要實現(xiàn)內(nèi)部的內(nèi)容。
package com.its.mmo;import java.beans.PropertyEditorSupport; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.commons.lang.StringUtils;/*** 日期格式話工具* SPRINGMVC日期字符換轉(zhuǎn)換Date* @author ALLEN*/ public class DateEditor extends PropertyEditorSupport {@Overridepublic void setAsText(String text) throws IllegalArgumentException {SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");Date date = null;try {if(StringUtils.isNotBlank(text)){date = format.parse(text);}} catch (ParseException e) {format = new SimpleDateFormat("yyyy-MM-dd");try {date = format.parse(text);} catch (ParseException e1) {e1.printStackTrace();}}setValue(date);} }然后在controller 中添加@InitBinder
/*** 初始化日期格式* * @param request* @param binder* @throws Exception*/@InitBinderprotected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {binder.registerCustomEditor(Date.class, new DateEditor());}?
轉(zhuǎn)載于:https://my.oschina.net/unteacher/blog/693266
總結(jié)
以上是生活随笔為你收集整理的SpringMVC 中设置日期字符串转换格式的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Apache多站点配置详解
- 下一篇: JSP 基础(一)