jackson Api错误,在Spring Boot中将时间戳显示为毫秒而不是日期(Jsonformat不工作)

mbzjlibv  于 2022-11-09  发布在  Spring
关注(0)|答案(1)|浏览(147)

我有一个关于显示时间戳作为 Spring 启动日期的问题。
我总是以如下所示的int值获取时间戳。

"timestamp": 1646735268046

我怎样才能得到它作为一个日期?
下面是我的ApiError实体。

@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;

}

下面是一个在全局异常处理类中定义的函数。

@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);
    }

编辑:

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

我仍然得到整型值。

wgeznvg7

wgeznvg71#

您使用的是LocalDateTime,但是在您的格式中有“Z”,这是LocalDateTime不支持的区域偏移。因此,要么更改为ZonedDateTimeOffsetDateTime,要么从您的格式中删除“Z”。除此之外,我看不出有任何问题。总之,这里有一个link to a similar question,它在这个主题上有一个很好的答案

相关问题