【问题标题】:Spring boot @RequestParam unix timestamp to LocalDateTime [duplicate]Spring引导@RequestParam unix时间戳到LocalDateTime [重复]
【发布时间】:2017-08-31 19:56:41
【问题描述】:

假设我的 RestController 中有

@GetMapping("/")
public list(@RequestParam LocalDateTime date) {
}

我使用日期请求参数作为 unix 时间戳发出 GET 请求,如下所示:

http://myserver.com/?date=1504036215944

如何让 Spring Boot 和 jackson 自动使用从 unix 时间戳到 LocalDateTime 的正确转换,而无需手动进行转换。

【问题讨论】:

标签: java spring spring-boot unix-timestamp


【解决方案1】:

解决方案:

@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

【讨论】:

    猜你喜欢
    • 2021-12-25
    • 2015-05-25
    • 2015-12-30
    • 2021-11-20
    • 2018-12-19
    • 1970-01-01
    • 1970-01-01
    • 2011-02-26
    • 2013-03-23
    相关资源
    最近更新 更多