如何在 Spring Boot Jackson 日期序列化中应用默认时区

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46151633/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:30:09  来源:igfitidea点击:

How to make default time zone apply in Spring Boot Hymanson Date serialization

springspring-mvcspring-bootHymansonHymanson2

提问by codependent

I have configured my Spring Boot application to serialize dates as ISO8601 strings:

我已将 Spring Boot 应用程序配置为将日期序列化为 ISO8601 字符串:

spring:
  Hymanson:
    serialization:
      write-dates-as-timestamps: false

This is what I am getting:

这就是我得到的:

"someDate": "2017-09-11T07:53:27.000+0000"

However my time zone is Europe/Madrid. In fact if I print TimeZone.getDefault()that's what I get.

但是我的时区是欧洲/马德里。事实上,如果我打印TimeZone.getDefault()这就是我得到的。

How can I make Hymanson serialize those datetime values using the actual timezone? GMT+2

如何让 Hymanson 使用实际时区序列化这些日期时间值?格林威治标准时间+2

"someDate": "2017-09-11T09:53:27.000+0200"

回答by Jaumzera

I found myself with the same problem. In my case, I have only one timezone for my app, then adding:

我发现自己遇到了同样的问题。就我而言,我的应用程序只有一个时区,然后添加:

spring.Hymanson.time-zone: America/Sao_Paulo

in my application.propertiessolved the problem.

在我application.properties解决了这个问题。

Source: https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html#HymanSON

来源:https: //docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html#HymanSON

回答by barbakini

You can set timezone for whole application with adding this to a config class:

您可以通过将其添加到配置类来为整个应用程序设置时区:

@PostConstruct
void started() {
    TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
}

回答by codependent

Solved registering a Hymanson2ObjectMapperBuilderCustomizer bean:

解决了注册 Hymanson2ObjectMapperBuilderCustomizer bean 的问题:

@Bean
public Hymanson2ObjectMapperBuilderCustomizer HymansonObjectMapperCustomization() {
    return HymansonObjectMapperBuilder -> 
        HymansonObjectMapperBuilder.timeZone(TimeZone.getDefault());
}

回答by Pramod

There are 2 solutions for this:

有两种解决方案:

1. Add JSON format annotation

1.添加JSON格式注释

@JsonFormat(shape = JsonFormat.Shape.STRING, timezone = "Asia/Kolkata")
private Date insertionTime;

2. Add Hymanson time zone to properties (spring boot)

2.在属性中添加Hymanson时区(spring boot)

spring.Hymanson.time-zone: America/Sao_Paulo

Reference :https://www.baeldung.com/spring-boot-formatting-json-dates

参考:https : //www.baeldung.com/spring-boot-formatting-json-dates