springmvc傳參---LocalDateTime、Date等時間類型轉換


此處定義的dateConvert用來轉換Date類型,如果是LocalDate、LocalDateTime類型,則將Date
類型換成相應的類型即可,注意java8的日期類型需要用Formatter格式化:

編寫一個這樣的類就可以了

 

/**
* 轉換解析器
* @author wangqingguo 2017/9/25
*/
@Configuration
public class MappingConverterAdapter {

/**
* 接收前端datetime參數
* @return
*/
@Bean
public Converter<String, LocalDateTime> LocalDateTimeConvert() {
return new Converter<String, LocalDateTime>() {
@Override
public LocalDateTime convert(String source) {

DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime date = null;
try {
date = LocalDateTime.parse((String) source,df);
} catch (Exception e) {
e.printStackTrace();
}
return date;
}
};
}


/**
* 返回LocalDateTime值(去掉LocalDateTime中的T)
*/
@org.springframework.beans.factory.annotation.Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
private String pattern;

@Bean
public LocalDateTimeSerializer localDateTimeDeserializer() {
return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern));
}

@Bean
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
return builder -> builder.serializerByType(LocalDateTime.class, localDateTimeDeserializer());
}


}


免責聲明!

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



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