javajacksonjackson2

How to format date using JsonFormat


I want to format the data using @JsonFormat and exclude the nanosecond.

[
  {
    "createtime": "2021-02-08 16:44:41.336475",
    "orderdate": "2021-02-03 22:55:54.764"
  },
  {
    "createtime": "2021-02-08 16:44:41.3365",
    "orderdate": "2021-02-03 22:55:54.4"
  }
]

The no of digits of nanoseconds is not fixed. Below is the code I've written

@JsonProperty("createtime")
@JsonFormat(shape = JsonFormat.Shape.STRING,pattern = "yyyy-MM-dd HH:mm:ss.SSSSSS")
private LocalDateTime createTime;

@JsonProperty("orderdate")
@JsonFormat(shape = JsonFormat.Shape.STRING,pattern = "yyyy-MM-dd HH:mm:ss.SSS")
private LocalDateTime orderDate;

when "createtime": 2021-02-08 15:14:41.33675, I'm getting Failed to deserialize java.time.LocalDateTime. Please advise me how can I format the date in yyyy-MM-dd HH:mm:ss format. Thanks in advance


Solution

  • Firstly, regarding your question about deserializing JSON data into a Java LocalDateTime property, you could use the following approach:

    class Timed {
      
        private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSS");
        
        @JsonIgnore
        private LocalDateTime createTime = LocalDateTime.now();
        
        public LocalDateTime getCreateTime() {
          return createTime;
        }
    
        public void setCreateTime(LocalDateTime createTime) {
          this.createTime = createTime;
        }
        
        @JsonProperty("createtime")
        public String createTime() {
          return formatter.format(createTime);
        }
     
        @JsonCreator
        public void setCreateTime(@JsonProperty("createtime") String property) {
          createTime = LocalDateTime.parse(json, formatter).truncatedTo(ChronoUnit.SECONDS);
        }
        
        @Override
        public String toString() {
          return "Timed{"createTime=" + createTime + '}';
        }
    }
    

    Update: You could completely remove the nanoseconds:

    private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        
    @JsonCreator
    public void setCreateTime(@JsonProperty("createtime") String property){
        String withoutNanos = property.split("\\.")[0];
        createTime = LocalDateTime.parse(withoutNanos, formatter);
    }