Json Date format in LocalDate

53 Views Asked by At

I have this annotation

@Target(ElementType.METHOD)
@Retention(value = RetentionPolicy.RUNTIME)
@JacksonAnnotationsInside
@Documented
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd", timezone = "Europe/Brussels")
public @interface MyDateFormat {
}

and this method:

  @MyDateFormat
    public LocalDate getCreationDate() {
        return Optional.ofNullable(task)
                .map(Task::getCreateTime)
                .map(date -> date.toInstant()
                        .atZone(ZoneId.systemDefault())
                        .toLocalDate())
                .orElse(null);
    }

but I got it in long format

1

There are 1 best solutions below

0
Mar-Z On BEST ANSWER

I have checked exactly the same code. It works as expected.

import com.fasterxml.jackson.annotation.JacksonAnnotationsInside;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(value = RetentionPolicy.RUNTIME)
@JacksonAnnotationsInside
@Documented
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd", timezone = "Europe/Brussels")
public @interface MyDateFormat {
}

@Transient
private Date createDate = new Date();

@MyDateFormat
public LocalDate getCreationDate() {
    return Optional.ofNullable(this)
            .map(Customer::getCreateDate)
            .map(date -> date.toInstant()
                    .atZone(ZoneId.systemDefault())
                    .toLocalDate())
            .orElse(null);
}

"createDate": "2023-05-11T06:45:24.044+00:00",
"creationDate": "2023-05-11"