1

I am returning a JSON as a response from the controller. I want to format the date fields in this response.

Controller-

@RequestMapping(value = "/call", method = RequestMethod.GET)
public SampleDTO get() 
{
    ......
    return sampleDTO;
}

SampleDTO-

{
   "date" : "2020-03-10T08:57:58+0000",
   "text" : "abc"
}

I want to format the date field to dd-MM-yyyy

To do this I add the @JsonFormat annotation to the bean class of SampleDTO.

SampleDTO.java -

import java.util.Date;
public class SampleDTO
{ 
    @JsonFormat(pattern = "dd-MM-yyyy") 
    private Date date;

    private String text;

    @JsonFormat(pattern = "dd-MM-yyyy") 
    public void setDate(final Date date)
    {
        this.date = date;
    }

    @JsonFormat(pattern = "dd-MM-yyyy") 
    public Date getDate() 
    {
        return date;
    }

    public void setText(final String text)
    {
        this.text = text;
    }

    public String getText() 
    {
        return text;
    }
}

Still, I am getting this format in the response on my browser.

"date" : "2020-03-10T08:57:58+0000"



EDIT 1:

Instead of returning the sampleDTO, converting it to String directly in the code works perfectly fine.

This works like a charm:

        SampleDTO sampleDTO = new SampleDTO();
        sampleDTO.setCreated(new Date());
        ObjectMapper om = new ObjectMapper();
        return om.writeValueAsString(sampleDTO);
2
  • 1
    Two recommendations: (1) Don’t use Date. That class is poorly designed and long outdated. Use LocalDate from java.time, the modern Java date and time API. (2) In your JSON use ISO 8601 format, so yyyy-MM-dd, not dd-MM-yyyy. Commented Mar 10, 2020 at 20:10
  • @OleV.V. : I see Date class all over the place in the latest version of Hybris. In my JSON I have a specific requirement to show the date in this format, so I can't change it. Commented Mar 11, 2020 at 9:27

4 Answers 4

2

Please, check that your Date is from java.util and not from java.sql package. Plus try the following:

@JsonSerialize(as = Date.class)
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="dd-MM-yyyy")
Sign up to request clarification or add additional context in comments.

2 Comments

@Farrukh Chishti, above should work, what version of jackson-databind.jar are you using?
@MOnkey : I am using 2.9.8
1

Could you try this on the field level and remove from getDate() method in your DTO.

Something like this,

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
private Date date;

This should work with your current version of jackson-databind:2.9.8.jar.

Here is the small example for you:

public class ExampleMain {

    public static void main(String[] args) throws IOException {
        Employee employee = new Employee();
        employee.setDateOfBirth(Date.from(ZonedDateTime.now().minusYears(30).toInstant()));

        System.out.println("-- before serialization --");
        System.out.println(employee);

        System.out.println("-- after serialization --");
        ObjectMapper om = new ObjectMapper();
        String jsonString = om.writeValueAsString(employee);
        System.out.println(jsonString);

        System.out.println("-- after deserialization --");
        System.out.println(om.readValue(jsonString, Employee.class));
    }
}

public class Employee {

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
    private Date dateOfBirth;


    public Date getDateOfBirth() {
        return dateOfBirth;
    }

    public void setDateOfBirth(Date dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
    }

    @Override
    public String toString() {
        return "Employee{" +
                ", dateOfBirth=" + dateOfBirth +
                '}';
    }
}

2 Comments

@Farrukh Chishti, try once the above changes.
I have made the suggested changes. Removing the annotation from getter and keeping the annotation on the field intact. No luck! In my code, the response is parsed automatically in the background. I am not using any mapper explicitly. I am simply returning the response as return sampleDTO
1

There are three levels of how you can solve this date format issue with Spring.

1) Using @JsonFormat on your date fields

In this case, you need to use the same annotation in front of all your private date members.

public class MyBean{

    @JsonFormat(pattern="yyyy-MM-dd")
    private Date birthday;

    @JsonFormat(pattern="yyyy-MM-dd")
    private LocalDate birthday;

    // getters and setters here
}

2) Setting the Default format

If you want to configure the default date format for all dates in your application, add the following line to the application.properties or application.yml config file:

spring.jackson.date-format=yyyy-MM-dd

Unfortunately, this solution doesn't work with the Java 8 date types, like LocalDate and LocalDateTime.

3) Customizing your Jackson ObjectMapper

This solution works like a charm with Java 8 date types as well.

@Configuration
public class ContactAppConfig {

    private static final String DATE_FORMAT = "yyyy-MM-dd";
    private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
        return builder -> {
            builder.simpleDateFormat(DATE_TIME_FORMAT);
            builder.serializers(new LocalDateSerializer(DateTimeFormatter.ofPattern(DATE_FORMAT)));
            builder.serializers(new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DATE_TIME_FORMAT)));
        };
    }
 }

I suggest you use the 3rd option.

2 Comments

Approach #1 is not working. Approach #2 will cause system-wide changes which, I don't want. Approach #3: Class Jackson2ObjectMapperBuilderCustomizer is missing in my codebase.
0

you can use jstl format to format the date :)

<%@ taglib prefix = "fmt" uri = "http://java.sun.com/jsp/jstl/fmt" %>
<fmt:formatDate pattern = "yyyy-MM-dd" value = "${date}" />

1 Comment

I want to simply change the format in the Webservice call i.e. in postman

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.