Search code examples
javajsontimestamptimestamp-with-timezone

Timestamp value getting modified on receving the response


I'm receiving a Timestamp via API in a Timestamp(java.sql) object and after some other validations I'm sending response as a JSON containing that same timestamp value, but the format in which I sent and in which I receive are not the same every time.

For example, if my JSON input has this value:
Case 1 :

"interval_time": "2022-01-26T12:00:00.511+05:30"

Reponse:

{
    "message": "Already contains result for timestamp : 2022-01-26 12:00:00.511",
    "httpcode": 409,
    "documentationLink": "",
    "status": "ERROR"
}

Notice the missing T and offset value 05:30.

Case 2:

"interval_end_time": "2022-01-26T12:00:00.511Z"

Response:

{
    "message": "Already contains result for timestamp : 2022-01-26 17:30:00.511",
    "httpcode": 409,
    "documentationLink": "",
    "status": "ERROR"
}

Notice the missing T and offset value got added in the timestamp.

I need a consistent response and it should be exactly what is being sent as an input. No change in timezone or offset.

For Case 1, response should come like this:

Reponse:

{
    "message": "Already contains result for timestamp : 2022-01-26T12:00:00.511+05:30",
    "httpcode": 409,
    "documentationLink": "",
    "status": "ERROR"
}

and for Case 2, it should be like this:

Response:

{
    "message": "Already contains result for timestamp : 2022-01-26T12:00:00.511Z",
    "httpcode": 409,
    "documentationLink": "",
    "status": "ERROR"
}

Note: The team is following the ISO 8601 standard.


Solution

  • I'm receiving a Timestamp via API in a Timestamp(java.sql) object

    No, you are not.

    You are receiving JSON text containing a string representing a moment in standard ISO 8601 format.

    Parse the string as a java.time.OffsetDateTime class.

    OffsetDateTime odt = OffsetDateTime.parse( "2022-01-26T12:00:00.511+05:30" ) ;
    

    Avoid the terribly flawed legacy date-time classes such as java.sql.Timestamp. Use only their replacement, the java.time classes.

    To generate text in ISO 8601 format, simply call OffsetDateTime#toString.

    String output = odt.toString() ;
    

    I'm using Gson to parse it to my Java class having a Timestamp data member.

    Don’t.

    Use only java.time classes.