25

在Spring Boot javascript:;中格式化JSON日期 - - SegmentFault 思否

 4 years ago
source link: https://segmentfault.com/a/1190000020897931
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

在Spring Boot javascript:;中格式化JSON日期

发布于 2019-11-04

pring Boot中格式化JSON日期1.概述
在本教程中,我们将展示如何在Spring Boot应用程序中格式化JSON日期字段。 我们将探讨使用Jackson格式化日期的各种方法,它被Spring Boot用作默认的JSON处理器。

2.在日期字段上使用@JsonFormat2.1设置格式
[Java] 纯文本查看 复制代码
?

public class Contact {

// other fields
@JsonFormat(pattern="yyyy-MM-dd")
private LocalDate birthday;
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
private LocalDateTime lastUpdate;
// standard getters and setters

在生日字段上,我们使用的格式只显示日期,而在 lastUpdate字段中我们也包含时间。 我们使用了Java 8日期类型,它们非常便于处理时态类型。当然,如果我们需要使用像java.util.Date 这样的遗留类型 ,我们可以以相同的方式使用注释:

[Java] 纯文本查看 复制代码
?

public class ContactWithJavaUtilDate {

 // other fields
 @JsonFormat(pattern="yyyy-MM-dd")
 private Date birthday;
 @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
 private Date lastUpdate;
 // standard getters and setters

}
最后,让我们看看使用给定日期格式的@JsonFormat 呈现的输出 :

[Java] 纯文本查看 复制代码
?

"birthday": "2019-02-03",
"lastUpdate": "2019-02-03 10:08:02"

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK