3

Use spring boot 2. It includes Jackson Java8 API already. But the JSON format for LocalDatetime is a human-readable format. I want to it be the EPOCH via the Jackson, just a real timestamp.

I know how to convert LocatDatetime to EPOCH in Java8 API. My question is how to config Spring Boot 2 to do that. Is that possible without add customer ObjectMapper?

Brian Clozel
  • 56,583
  • 15
  • 167
  • 176
Chris
  • 6,431
  • 10
  • 44
  • 59
  • 1
    Possible duplicate of [How to extract epoch from LocalDate and LocalDateTime?](https://stackoverflow.com/questions/22990067/how-to-extract-epoch-from-localdate-and-localdatetime) – Daniel Eisenreich Dec 20 '17 at 06:32
  • @DanielEisenreich my question is how to config it in the Spring Boot 2 Application, not in pure Java8 API – Chris Dec 20 '17 at 09:54
  • Whats about using the `JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "s")` annotation? – Daniel Eisenreich Dec 20 '17 at 10:58

1 Answers1

10

Try to set these properties in application.yml

spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS: true
spring.jackson.serialization.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS: false
Mikita Harbacheuski
  • 2,193
  • 8
  • 16
  • As I remember the WRITE_DATES_AS_TIMESTAMPS is defaulted to true. The interesting thing is when I explicitly set this value to true. It works half as expected. The result is like `{ "timestamp": 1513824072.458000000 }`, can we remove the value after the decimal point. – Chris Dec 21 '17 at 02:42
  • Found the reason, the spring boot 2, change the Jackson default value of WRITE_DATES_AS_TIMESTAMPS to false. But for the LocalDateTime the timestamp value is incorrect it should be 1513824072458 not 1513824072.458000000 – Chris Dec 21 '17 at 03:05
  • You'll want to use Instant.now() if you're developing web services. Here is a link: https://stackoverflow.com/questions/32437550/whats-the-difference-between-instant-and-localdatetime/32443004#32443004 – TheJeff Jun 12 '19 at 15:56