SpringMVC對日期類型的轉(zhuǎn)換示例
在做web開發(fā)的時候,頁面?zhèn)魅氲亩际荢tring類型,SpringMVC可以對一些基本的類型進行轉(zhuǎn)換,但是對于日期類的轉(zhuǎn)換可能就需要我們配置。
1、如果查詢類使我們自己寫,那么在屬性前面加上@DateTimeFormat(pattern = "yyyy-MM-dd") ,即可將String轉(zhuǎn)換為Date類型,如下
@DateTimeFormat(pattern = "yyyy-MM-dd") private Date createTime;
2、如果我們只負責(zé)web層的開發(fā),就需要在controller中加入數(shù)據(jù)綁定:
@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); //true:允許輸入空值,false:不能為空值
3、可以在系統(tǒng)中加入一個全局類型轉(zhuǎn)換器
實現(xiàn)轉(zhuǎn)換器
public class DateConverter implements Converter<String, Date> {
@Override
public Date convert(String source) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
try {
return dateFormat.parse(source);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
進行配置:
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="com.doje.XXX.web.DateConverter" />
</list>
</property>
</bean>
<mvc:annotation-driven conversion-service="conversionService" />
4、如果將日期類型轉(zhuǎn)換為String在頁面上顯示,需要配合一些前端的技巧進行處理。
5、SpringMVC使用@ResponseBody返回json時,日期格式默認顯示為時間戳。
@Component("customObjectMapper")
public class CustomObjectMapper extends ObjectMapper {
public CustomObjectMapper() {
CustomSerializerFactory factory = new CustomSerializerFactory();
factory.addGenericMapping(Date.class, new JsonSerializer<Date>() {
@Override
public void serialize(Date value, JsonGenerator jsonGenerator,
SerializerProvider provider) throws IOException, JsonProcessingException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
jsonGenerator.writeString(sdf.format(value));
}
});
this.setSerializerFactory(factory);
}
}
配置如下:
<mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="objectMapper" ref="customObjectMapper"></property> </bean> </mvc:message-converters> </mvc:annotation-driven>
6、date類型轉(zhuǎn)換為json字符串時,返回的是long time值,如果需要返回指定的日期的類型的get方法上寫上@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8") ,即可將json返回的對象為指定的類型。
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
public Date getCreateTime() {
return this.createTime;
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot2.0.3打印默認數(shù)據(jù)源為 HikariDataSource (null)問題
這篇文章主要介紹了SpringBoot2.0.3打印默認數(shù)據(jù)源為 HikariDataSource (null)問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-10-10
Java輸入流Scanner/BufferedReader使用方法示例
這篇文章主要介紹了Java輸入流Scanner/BufferedReader使用方法,大家看示例吧2013-11-11

