When I was making a RESTful API with Spring Boot, I wanted to format the Date type of the response to ISO 8601 extended format and return it. It took a long time to find the format, so I will leave it as a memorandum.
It can be output with yyyy-MM-dd'T'HH: mm: ssXXX.
Test.java
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test {
        public static void main(String[] args) {
                Date d = new Date();
                SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
                System.out.println(sf.format(d));
        }
}
2018-12-19T15:46:06+09:00
If you are using Spring Boot, you should be using ** Jackson ** as the JSON conversion of the response. You can specify the default format by adding the following settings to ʻapplication.yml`.
application.yml
spring:
  jackson:
      date-format: "yyyy-MM-dd'T'HH:mm:ssXXX"
      time-zone: "Asia/Tokyo"
Jackson will be ** GMT if you don't specify a timezone **. Basically, I think it's better to specify the time zone.
If you want to convert the format explicitly instead of the default format, write as follows.
Response.java
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
public class Response {
    @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ssXXX", timezone = "Asia/Tokyo")
    private Date createdAt;
    public Date getCreatedAt() {
        return createdAt;
    }
    public void setCreatedAt(Date createdAt) {
        this.createdAt = createdAt;
    }
}
The format is slightly different for each language, so it's surprisingly addictive. Isn't it all unified?
Recommended Posts