2

Let's say I have in my RestController

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

and I make a GET request with date request param as unix timestamp like this:

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

How do I make Spring Boot and jackson to use the correct conversion from unix timestamp to LocalDateTime automatically without manually doing the conversion.

danial
  • 4,058
  • 2
  • 32
  • 39

1 Answers1

0

A solution:

@GetMapping("/")
public @ResponseBody String list(TimestampRequestParam date) {
    return date.toString();
}

Implementing the time stamp to date converter in setDate

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
whoopdedoo
  • 2,815
  • 23
  • 46