Simple Date format not recognised

184 Views Asked by At

I am on Windows 10 with Java 17 using Simple Date Format.

I am trying to get a date format like 2023-10-12 21:26:16 but instead I get 2023-Oct-12 21:26:16. The date is inside a Jackson 2.15 ObjectMapper.

This is my code:

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ", new Locale("en", "NZ")));
ErrorMessage errorMessage = new ErrorMessage();
...
String jsonMessage =  objectMapper.writeValueAsString(errorMessage.builder()
        .message(mostSpecificCauseMessage)
        .timeStamp(sdf.format(System.currentTimeMillis()))
        .build());

What am I missing and how can I get a date with 2023-10-12 .... vs 2023-Oct-12...?

2

There are 2 best solutions below

2
mipo256 On BEST ANSWER

There are a couple of things to consider:

First, your ErrorMessage class has a timestamp field, which is either String or StringBuffer, but not a date (because you are setting it via sdf.format(System.currentTimeMillis())). Therefore, for this timestamp field the line :

objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ", new Locale("en", "NZ")));

does not do essentially anything, since for jackson timestamp field is just the String/StringBuffer, not a any java date/time api class.

Second - what does sdf look like in your case? This is what actually formats passed milliseconds from epoch. If it looks like yyyy-MM-dd HH:mm:ss.SSSZ, then you should get the result that you want. For more detailed explanation you should provide a pattern that is backing the sdf.

0
Peng On

there may be potential cause in your code which the date column in your json , would be string , not date , so you can have a try for following code snippet , it could help you realize issue.


    @Test
    @SneakyThrows
    public void test () {
        ObjectMapper objectMapper = new ObjectMapper();

// Configure the date format with a specific locale
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ", new Locale("en", "NZ"));
        objectMapper.setDateFormat(sdf);

// Create an instance of ErrorMessage and set its properties
// ...

// Serialize the ErrorMessage object to a JSON string
        String jsonMessage = objectMapper.writeValueAsString(new Date());
        System.out.println(jsonMessage);
    }

and this the result

"2023-10-12 08:56:57.984+0000"