1

I try to take a string who contain a vlaue of zoneDateTime.

ObjectMapper objectMapper = new ObjectMapper().registerModule(new JavaTimeModule()).disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
String date = "2019-06-12T22:00:00-04:00";
OffsetDateTime odt = objectMapper.readValue(date, OffsetDateTime.class);
System.out.println(odt);

Jackson said: parserException: unexpected character -

This command is valid

OffsetDateTime.parse("2019-06-12T22:00:00-04:00"); 

So seem like a jackson issue

robert trudel
  • 5,283
  • 17
  • 72
  • 124

1 Answers1

1

The objectMapper.readValue(date, OffsetDateTime.class) expects the string date to be valid JSON.

So, one way to use this would be to start with an example such as the following:

String json = "{ \"odt\" : \"2019-06-12T22:00:00-04:00\" }";

And then create an object to store this JSON, for example:

import java.time.OffsetDateTime;

public class ODT {

    private OffsetDateTime odt;

    public OffsetDateTime getOdt() {
        return odt;
    }

    public void setOdt(OffsetDateTime odt) {
        this.odt = odt;
    }
    
}

Now, the following code will handle the input successfully, using your object mapper:

ODT myOdt = objectMapper.readValue(json, ODT.class);
System.out.println(myOdt.getOdt());

This prints:

2019-06-13T02:00Z

Update

To display this value using the original offset, instead of UTC, you can use the following:

System.out.println(myOdt.getOdt().atZoneSameInstant(ZoneId.of("-04:00")));

This prints:

2019-06-12T22:00-04:00

This is the same as the original value in our starting JSON string.

andrewJames
  • 19,570
  • 8
  • 19
  • 51
  • Locally, I have new york time. zone.. so -4 i was expected to get 2019-06-12T18:00 – robert trudel Jul 23 '20 at 15:42
  • Understood - I have updated my answer to cover your point (but it should be 22:00 not 18:00, right?). Since the original time was 22:00 in the -04:00 offset, that would be 02:00 the next day in UTC time (as shown in my initial answer). So, re-adjusting the display string for this offset takes us back to the starting time. Hope that makes sense. – andrewJames Jul 23 '20 at 16:15