前言
我们的小程序中出现了一个问题,那就是页面显示的时间与数据库中保存的时间有八个小时的时差。数据库中的保存的时间是正确的,但是显示到页面上就错误了,能猜到可以通过配置文件的方式来解决。
方法一
添加jackson的配置,来配置时间格式,并且把时区设定为自己国家
spring: jackson: date-format: yyyy-MM-dd HH:mm:ss default-property-inclusion: non_empty time-zone: Asia/Shanghai
方法二
这种方法比较推荐,直接使用配置类的方式来进行配置
package work.huangxin.share.config; import com.fasterxml.jackson.databind.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; import java.text.SimpleDateFormat; import java.util.List; import java.util.TimeZone; /** * @author: 张锦标 * @date: 2023/4/24 18:43 * JsonConfig类 */ @Configuration public class JsonConfig extends WebMvcConfigurationSupport { private static final Logger LOGGER = LoggerFactory.getLogger(JsonConfig.class); @Override public void addInterceptors(InterceptorRegistry registry) { //请求上下文初始化拦截器配置 LOGGER.info("初始化拦截器完成....."); } @Override protected void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); } @Bean public ObjectMapper jacksonObjectMapperCustomization() { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); TimeZone timeZone = TimeZone.getTimeZone("Asia/Shanghai"); format.setTimeZone(timeZone); Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder() .timeZone(timeZone) .dateFormat(format); return builder.build(); } @Override protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) { converters.removeIf(c -> c instanceof MappingJackson2HttpMessageConverter); converters.add(new MappingJackson2HttpMessageConverter(jacksonObjectMapperCustomization())); } }
方法三
这种方式就是直接使用注解的方式来完成
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")