@JsonFormat pattern for LocalTime



我有这个字段

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss'Z'")
private Date completionDate;
我得到这个结果:2021-10-05T14:17:16Z

我需要把这个日期分成两个字段:

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
@JsonDeserialize(using = LocalDateDeserializer.class)
@JsonSerialize(using = LocalDateSerializer.class)
private LocalDate date;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = ???)
@JsonDeserialize(using = LocalTimeDeserializer.class)
@JsonSerialize(using = LocalTimeSerializer.class)
private LocalTime time;

我知道我应该在日期部分使用什么。但是时间部分需要什么样的模式呢?"HH:mm:ss'Z'"?

java.time

java.utilDate-Time API及其格式化API,SimpleDateFormat是过时的,容易出错。建议完全停止使用它们,切换到现代的Date-Time API*

不要混合使用旧的和现代的Date-Time API:在您的代码中,您将容易出错的遗留Date-Time API与现代Date-Time API混合在一起,这将使您的代码不必要地复杂和容易出错。我建议您将completionDate声明为ZonedDateTime,您可以从中检索日期和时间部分,如下面的示例所示:

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
ZonedDateTime completionDate = ZonedDateTime.now(ZoneId.of("Etc/UTC"));
LocalDate date = completionDate.toLocalDate();
LocalTime time = completionDate.toLocalTime();
System.out.println(completionDate);
System.out.println(date);
System.out.println(time);
// Some examples of custom formats
DateTimeFormatter dtfTime = DateTimeFormatter.ofPattern("HH:mm:ss", Locale.ENGLISH);
System.out.println(time.format(dtfTime));
DateTimeFormatter dtfDtTz = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssXXX", Locale.ENGLISH);
System.out.println(completionDate.format(dtfDtTz));
}
}

输出:

2021-10-06T08:56:37.131679Z[Etc/UTC]
2021-10-06
08:56:37.131679
08:56:37
2021-10-06T08:56:37Z
<<p>

在线演示/kbd>从Trail: Date Time了解更多关于现代Date-Time API的信息.


*如果你正在为一个Android项目工作,你的Android API级别仍然不兼容Java-8,检查Java 8+可用的API。注意Android 8.0 Oreo已经提供了对java.time的支持。

最新更新