假设我的 RestController 中有
@GetMapping("/")
public list(@RequestParam LocalDateTime date) {
}
我使用日期请求参数作为 unix 时间戳发出 GET 请求,如下所示:
http://myserver.com/?date=1504036215944
如何使 Spring Boot 和 jackson 自动使用从 unix 时间戳到 LocalDateTime 的正确转换,而无需手动进行转换。
一个办法:
@GetMapping("/")
public @ResponseBody String list(TimestampRequestParam date) {
return date.toString();
}
在 setDate 中实现时间戳到日期转换器
注意 getter & setter 必须有参数名称(类成员可以有不同的名称)
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);
}
}
输出示例(注意端口,您可能配置不同)
$ curl localhost:8080?date=1504036215944
timestamp2date : 2017-08-29 22:50:15.944
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)