Search code examples
javadatetimejacksonsimpledateformatobjectmapper

Simple Date format not recognised


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...?


Solution

  • 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.