javaspring-bootsimpledateformatdate-conversion

How to convert Date from 2023-11-10 09:44:00.038860 to 2023-11-10T09:44:20.001+00:00 in spring boot application


I am getting response from ELK and mapping it to an object using ObjectMapper and then return the response as JSON. The ELK response has a Date datatype field with the format yyyy-MM-dd HH:mm:ss.SSSSSS. The ELK response retrieved is in UTC and I want the API JSON response to be in UTC as well. So no timezone conversion required. I want the JSON payload to display the Date field in the format 2023-11-09T03:00:35.563+00:00. It tried to set @JsonFormat on the field but did not work.

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS")
private Date timestamp;

I tried using multiple formats yyyy-MM-dd'T'HH:mm:ss.SSSX or yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. But throws the same exception.

Also tried the following ,

SimpleDateFormat out = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSS");
mapper.setDateFormat(out);
SimpleDateFormat in = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
SimpleDateFormat out = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSS");
String dateIn = in.format(Obj.getTimestamp());
Date dateOut = out.parse(dateIn);

Am I using the correct format for 2023-11-09T03:00:35.563+00:00? The exception thrown is Exception thrown [Cannot deserialize value of type java.util.Date from String "2023-11-10 09:44:00.038860": expected format " yyyy-MM-dd'T'HH:mm:ss.SSSSSS" or unparseable date exception is thrown. Thanks!


Solution

  • String manipulation

    In your case, the simplest approach is mere string manipulation.

    String input = "2023-11-10 09:44:00.038860" ;
    String result = 
        input
        .replace( " " , "T" )
        .substring( 0 , 24 )
        .concat( "+00:00" )
    ;