When I execute the following code:
System.out.println(new ObjectMapper().configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false).writeValueAsString(new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse("April 12, 2001")));
I see the output:
"2001-04-12T04:00:00.000+00:00"
I am trying to understand where the 04 after the T is coming from? My Jackson dependency:
implementation("com.fasterxml.jackson.core", "jackson-databind", "2.11.1")
This happens because you're not specifying time and timezone, so output contains date-time in UTC timezone. Your system has timezone UTC-4
, so, 4 hours are added to the date you've provided.
My timezone is UTC+3
, so the output I'm getting
"2001-04-11T21:00:00.000+00:00"
I would recommend using Java 8 time for such cases, so you can always be sure what output you'll receive.
Following code outputs
"2001-04-12T00:00:00Z"
regardless your local timezone.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM d, yyyy", Locale.ENGLISH);
System.out.println(new ObjectMapper().registerModule(new JavaTimeModule()).configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false).writeValueAsString(LocalDate.parse("April 12, 2001", formatter).atStartOfDay().atOffset(ZoneOffset.UTC)));
P.S.
You can play around with parsed LocalDate
and it's not necessary to convert it to OffsetDateTime