0

I have a problem about showing timestamp as a Date in Spring boot.

I always get timestamp as an int value shown below.

"timestamp": 1646735268046

How can I get it as a Date?

Here is my ApiError entity shown below.

@Data
@AllArgsConstructor
public class ApiError implements Serializable {

    private int statusCode;

    private HttpStatus status;

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss'Z'", timezone = "GMT")
    private LocalDateTime timestamp;

    private String message;

    List<String> errorDetails;

}

Here is a function defined in Global Exception Handling class shown below.

    @ExceptionHandler(UserNotFoundException.class)
    public ResponseEntity<Object> handleRefreshTokenException(RefreshTokenException ex) {

        List<String> details = new ArrayList<String>();
        details.add(ex.getMessage());

        ApiError err = new ApiError(HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST, LocalDateTime.now() ,
                "User Not Found", details);

        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(err);
    }

Edited:

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime timestamp;

I still get int value.

S.N
  • 2,157
  • 3
  • 29
  • 78
  • first of all, you are getting `long` not `int`. Integers in Java can have max of `2^31 - 1`. can you please mention spring/boot version, if you are using that, that way we can know what jackson version you are using, OR are you using jackson explicitely (or something else)? – Anil Bhaskar Mar 11 '22 at 06:52

1 Answers1

0

You are using LocalDateTime but in your format you have 'Z' which is zone-offset which is not supported by LocalDateTime. So either change to ZonedDateTime or OffsetDateTime or remove 'Z' from your format. Other than that I don't see any problems. Anyway here is a link to a similar question with a very good answer on this topic

Michael Gantman
  • 7,315
  • 2
  • 19
  • 36