Search code examples
spring-bootjackson-databind

Converting java.sql.timestamp to millisecond format


I have a private java.sql.Timestamp myDate in some model (POJO) class like below

private String isActive;
private Date dob;
private Timestamp createdDate;
private Timestamp lastMktPrefUpdateAt;

We were using spring boot version to 1.5.10.RELEASE and REST API response for timestamp field was in millisecond format like below -

   {
        "isActive": "y",
        "lastMktPrefUpdateAt": 1632195609787,
        "dob": "08/12/1991",
        "createdDate": 1632195609788
    }

We have recently upgraded the spring boot version to 2.3.0.RELEASE and this started sending timestamp field in response to some ISO format like below -

  {
        "isActive": "y",
        "lastMktPrefUpdateAt": "2021-09-20T22:10:09.787+0000",
        "dob": "07/12/1991",
        "createdDate": "2021-09-20T22:10:09.788+0000"
    }

Can someone please help answering, how can we format Timestamp back to millisecond format? We need to format Timestamp at global level meaning without changing all the POJO classes.


Solution

  • Try this in your properties file

    spring.jackson.serialization.write-dates-as-timestamps:true
    

    OR
    Use @JsonFormat(shape = JsonFormat.Shape.NUMBER) above the property that you want.

    Update

    If you want to add millis to your timestamp, try to pass the long value to the Timestamp constructor and call the getTime() method to receive a 13-digits timestamp.

       long now = System.currentTimeMillis();
       Timestamp timeStamp= new Timestamp(now);
       System.out.println(timeStamp.getTime());