问题描述
假设我在 RestController 中有一个
Let's say I have in my RestController
@GetMapping("/")
public list(@RequestParam LocalDateTime date) {
}
并且我使用日期请求参数作为 unix 时间戳发出一个 GET 请求,如下所示:
and I make a GET request with date request param as unix timestamp like this:
http://myserver.com/?date=1504036215944
如何让 Spring Boot 和 jackson 自动使用从 unix 时间戳到 LocalDateTime 的正确转换,而无需手动进行转换.
How do I make Spring Boot and jackson to use the correct conversion from unix timestamp to LocalDateTime automatically without manually doing the conversion.
推荐答案
一个解决方案:
@GetMapping("/")
public @ResponseBody String list(TimestampRequestParam date) {
return date.toString();
}
在 setDate 中实现时间戳到日期转换器
Implementing the time stamp to date converter in setDate
注意 getter &setter 必须有参数名(类成员可以有不同的名字)
pay attention that the getter & setter must have the parameter name ( the class member can have different name )
class TimestampRequestParam {
private Date date; // member name doesn't need to be like request parameter
private static final SimpleDateFormat FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
public Timestamp2DateExample() { }
// must have the same name as the request param
public Date getDate() {
return date;
}
/**
* @param timestamp
* here we convert timestamp to Date, method name must be same as request parameter
*/
public void setDate(String timestamp) {
long longParse = Long.parseLong(timestamp);
this.date = new Date(longParse);
}
@Override
public String toString() {
return "timestamp2date : " + FORMAT.format(date);
}
}
输出示例(注意端口,你可能配置不同)
Output example (pay attention to the port, you might configured differently)
$ curl localhost:8080?date=1504036215944
timestamp2date : 2017-08-29 22:50:15.944
这篇关于Spring boot @RequestParam unix 时间戳到 LocalDateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!