Utkarsh Gandhi
Utkarsh Gandhi

Reputation: 645

Jackson @JsonFormat converting date with incorrect timezone

I have a value coming in from JSON payload as:

"callStartTime" : "2019-03-27 13:00:00"

Entity.java

@JsonProperty("callStartTime")
@Column(name = "call_start_dt", nullable = false)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", lenient = OptBoolean.FALSE)
private Date callStartTime;

When I printed it on console, it says:

Wed Mar 27 08:00:00 CDT 2019

I wanted to be the same as it was in json payload. How I can fix it?

I am just taking date from json and writing it to mysql db in a datetime column.

Upvotes: 3

Views: 16672

Answers (4)

Pramod H G
Pramod H G

Reputation: 1613

There are two possible solutions for this :

1. Define ObjectMapper bean and set date format.

@Bean
public ObjectMapper objectMapper()
{
   ObjectMapper objectMapper = new ObjectMapper();

   DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
   objectMapper.setDateFormat(df);
       return objectMapper;
}

2. Set date format for the particular field using @JsonFormat

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", lenient = OptBoolean.FALSE)
private Date createTime;

Upvotes: -1

Utkarsh Gandhi
Utkarsh Gandhi

Reputation: 645

Simple solution: I solved it by changing the data type to String which completes my aim to capture the value as it is coming from JSON payload. Using Date and other data types were converting the value to some different timezone.

@JsonProperty("callStartTime")
@Column(name = "call_start_dt", nullable = false)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", lenient = OptBoolean.FALSE)
private **String** callStartTime;

Upvotes: 3

Not a JD
Not a JD

Reputation: 1902

java.util.Date does not capture time zone data. It only knows about number of millis since the epoch.

You could try using one of the modules in jackson-modules-java8 and deserialize into an instance of ZonedDateTime instead, which is time-zone aware.

EDIT: try this as a basis for getting it to work:

public class SoTest {
    public static void main(String[] args) throws Exception {
        ObjectMapper om = new ObjectMapper().registerModule(new ParameterNamesModule())
                                            .registerModule(new JavaTimeModule());

        String s = "{\"callStartTime\" : \"2019-03-27T13:00:00Z\" }";

        MyType mt = om.readValue(s, MyType.class);

        System.out.println(mt.getCallStartTime());
    }
}

class MyType {
    @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ssX", lenient = OptBoolean.FALSE)
    private ZonedDateTime callStartTime;

    public ZonedDateTime getCallStartTime() {
        return callStartTime;
    }

    public void setCallStartTime(ZonedDateTime date) {
        this.callStartTime = date;
    }

}

Upvotes: -1

codiallo
codiallo

Reputation: 183

Try this

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

Upvotes: 0

Related Questions