SpringMVC寫一個時間格式轉換器(三種方法)


第一種方法:

在變量處直接添加@DateTimeFormat(pattern="yyyy-MM-dd")

 

第二種方法:

1.首先新建一個DataConverter實現Converter接口的工具類

package util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

import org.springframework.core.convert.converter.Converter;

import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException;

public class DataConverter implements Converter<String, Date> {

	public Date convert(String source) {
		//編寫時間轉換器,支持多種時間格式
				SimpleDateFormat sdf = getSimpleDateFormat(source);
				try {
					Date date = sdf.parse(source);
					return date;
				} catch (ParseException e) {
					e.printStackTrace();
				} catch (java.text.ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		return null;
	}
	private SimpleDateFormat getSimpleDateFormat( String source ) {
		SimpleDateFormat sdf = new SimpleDateFormat();
		if( Pattern.matches("^\\d{4}-\\d{2}-\\d{2}$", source )) {
			sdf = new SimpleDateFormat("yyyy-MM-dd");
		} else {
			System.out.println("日期格式錯誤");
		}
		return sdf;
	}
}

  2.在配合文件中加上

<!-- 注冊轉化器 -->
    <mvc:annotation-driven conversion-service="conversion-service"/>    
    <!-- 轉換器服務工廠Bean -->
    <bean id="conversion-service"
        class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="util.DataConverter" /><!--工具類的class路徑-->
            </set>
        </property>
    </bean>

  第三種方法:

1,首先建工具類

package util;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

public class MyDateConverter {
	@InitBinder
    public void initBinder(WebDataBinder binder) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
    }
}

 2.讓controller繼承上面這個類


免責聲明!

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



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