一、需求
项目中使用java8的LocalDateTime进行日期参数的接收,前后台使用unix时间戳进行日期传输,需要在controller的方法中实现自动将unix时间戳转换为LocalDateTime。
localhost:8080?time=1512900770
public void test(@RequestParam LocalDateTime time) {
System.out.println(time);
}二、实现
使用Java配置
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
@Component
public class LocalDateTimeConverter implements Converter<String, LocalDateTime>{
@Override
public LocalDateTime convert(String source) {
return LocalDateTime.ofInstant(Instant.ofEpochSecond(Long.parseLong(source)), ZoneId.systemDefault());
}
}三、注意
仅仅对controller层方法参数中的LocalDateTime生效,不适用reqestBody的对象中的属性,对象中的属性可以自定义jackson的转换来实现。
未经允许请勿转载:程序喵 » SpringMVC全局参数转换——linux时间戳转换LocalDateTime
程序喵