SpringBoot如何根据用户系统时区动态展示时间

 更新时间:2023年01月06日 16:15:00   作者:RealJt  
这篇文章主要介绍了SpringBoot如何根据用户系统时区动态展示时间,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

根据用户系统时区动态展示时间

当我们使用SpringBoot+Mysql开发系统时,总是统一设置UTC+8时区,这样用户在任何地区访问系统,展示的时间都是国内标准时间,体验不友好,下面通过获取当前用户系统所在的时区,给用户展示不同的时间。

一、用户时区的获取

我们可以通过JavaScript来获取系统所在的时区,然后统一设置在请求头里。

Intl.DateTimeFormat().resolvedOptions().timeZone; // Asia/Shanghai

二、核心代码

这里统一使用LocalDateTime,更方便的处理时区转换问题,通过标识当前LocalDateTime对象所属时区,然后转换为目标时区时间。

public LocalDateTime convertLocalDateTime(LocalDateTime localDateTime, ZoneId originZoneId,
			ZoneId targetZoneId)
{
	return localDateTime.atZone(originZoneId).withZoneSameInstant(targetZoneId).toLocalDateTime();
}

三、SpringBoot返回json时统一处理时区

当程序从数据库中读取出并转换成LocalDateTime对象,并经过业务逻辑处理,这时候该对象还是属于UTC+8时区,对应的ZoneId=Asia/Shanghai,当需要返回给前端时,可以通过自定义jackson序列化器,在LocalDateTime转json前转换到用户目标时区。

@Configuration
public class JacksonConfiguration
{
	@Autowired
	private JacksonProperties jacksonProperties;	/**
	 * 时区转换
	 * 
	 * @param localDateTime
	 * @param originZoneId
	 * @param targetZoneId
	 * @return
	 */
	public static LocalDateTime convertLocalDateTime(LocalDateTime localDateTime, ZoneId originZoneId,
			ZoneId targetZoneId)
	{
		return localDateTime.atZone(originZoneId).withZoneSameInstant(targetZoneId).toLocalDateTime();
	}	/**
	 * LocalDateTime序列化
	 */
	public static class CustomLocalDateTimeSerializer extends JsonSerializer<LocalDateTime>
	{
		private DateTimeFormatter formatter;		public CustomLocalDateTimeSerializer(DateTimeFormatter formatter)
		{
			super();
			this.formatter = formatter;
		}		@Override
		public void serialize(LocalDateTime value, JsonGenerator generator, SerializerProvider provider)
				throws IOException
		{
			generator.writeString(convertLocalDateTime(value, ZoneId.of("Asia/Shanghai"), ZoneId.of("Africa/Sao_Tome"))
					.format(formatter));
		}	}	/**
	 * LocalDateTime反序列化
	 * 
	 */
	public static class CustomLocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime>
	{
		private DateTimeFormatter formatter;		public CustomLocalDateTimeDeserializer(DateTimeFormatter formatter)
		{
			super();
			this.formatter = formatter;
		}		@Override
		public LocalDateTime deserialize(JsonParser parser, DeserializationContext context)
				throws IOException, JacksonException
		{
			return convertLocalDateTime(LocalDateTime.parse(parser.getText(), formatter), ZoneId.of("Africa/Sao_Tome"),
					ZoneId.of("Asia/Shanghai"));
		}	}	@Bean
	public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer()
	{
		return builder ->
		{
			builder.serializerByType(LocalDateTime.class,
					new CustomLocalDateTimeSerializer(DateTimeFormatter.ofPattern(jacksonProperties.getDateFormat())));
			builder.deserializerByType(LocalDateTime.class,
					new CustomLocalDateTimeDeserializer(DateTimeFormatter.ofPattern(jacksonProperties.getDateFormat())));
		};
	}
}

上面示例代码设定用户时区ZoneId=Africa/Sao_Tome,并且自定义处理了LocalDateTime反序列化器,当使用ResquestBody注解时,对象中的LocalDateTime属性值也会转换成UTC+8时区,不用再额外处理,可直接保存到数据库。

四、SpringBoot接收时间参数统一处理时区

除了上面所说通过ResquestBody注解来接收参数外,还可能通过Get或者Post参数来接收LocalDateTime对象,这时候我们就要自定义一个Converter来处理String转换到LocalDateTime,同时把用户提交的属于用户时区的对象转换成UTC+8时区对象。

@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer
{
	@Autowired
	private WebMvcProperties webMvcProperties;	@Override
	public void addFormatters(FormatterRegistry registry)
	{
		registry.addConverter(new Converter<String, LocalDateTime>()
		{			private LocalDateTime convertLocalDateTime(LocalDateTime localDateTime, ZoneId originZoneId,
					ZoneId targetZoneId)
			{
				return localDateTime.atZone(originZoneId).withZoneSameInstant(targetZoneId).toLocalDateTime();
			}			@Override
			public LocalDateTime convert(String source)
			{
				return convertLocalDateTime(
						LocalDateTime.parse(source,
								DateTimeFormatter.ofPattern(webMvcProperties.getFormat().getDateTime())),
						ZoneId.of("Africa/Sao_Tome"), ZoneId.of("Asia/Shanghai"));
			}		});
	}}

五、总结

通过上面的处理,JavaScript负责获取用户时区,并且每次请求时带到后台,后台在接收请求和返回前端时统一转换用户时区,业务处理时不必再考虑时区问题。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • 浅谈关于Java正则和转义中\\和\\\\的理解

    浅谈关于Java正则和转义中\\和\\\\的理解

    这篇文章主要介绍了浅谈关于Java正则和转义中\\和\\\\的理解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-08-08
  • 深入了解Java 脚本化api编程

    深入了解Java 脚本化api编程

    Java 脚本 API 是一种独立于框架的脚本语言,使用来自于Java代码的脚本引擎 。可以使用Java语言编写定制/可扩展的应用程序并将自定义脚本语言选择留给最终用户 。下面我们来详细了解一下吧
    2019-06-06
  • xml与Java对象的转换详解

    xml与Java对象的转换详解

    这篇文章主要介绍了xml与Java对象的转换详解的相关资料,需要的朋友可以参考下
    2017-04-04
  • Java 基于Jakarta Mail实现收发邮件

    Java 基于Jakarta Mail实现收发邮件

    这篇文章主要介绍了Java 基于Jakarta Mail实现收发邮件的功能,帮助大家更好的理解和学习使用Java,感兴趣的朋友可以了解下
    2021-04-04
  • SpringBoot集成内存数据库H2的实践

    SpringBoot集成内存数据库H2的实践

    h2是内存数据库,查询高效,可以在开发初期使用它。本文主要介绍了SpringBoot集成内存数据库H2的实践,具有一定的参考价值,感兴趣的可以了解一下
    2021-09-09
  • SpringBoot通过自定义注解实现配置类的自动注入的实现

    SpringBoot通过自定义注解实现配置类的自动注入的实现

    本文主要介绍了SpringBoot通过自定义注解实现配置类的自动注入的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-04-04
  • IntelliJ IDEA中程序包org.slf4j找不到的解决

    IntelliJ IDEA中程序包org.slf4j找不到的解决

    这篇文章主要介绍了IntelliJ IDEA中程序包org.slf4j找不到的解决,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-11-11
  • Java实战之基于swing的QQ邮件收发功能实现

    Java实战之基于swing的QQ邮件收发功能实现

    这篇文章主要介绍了Java实战之基于swing的QQ邮件收发功能实现,文中有非常详细的代码示例,对正在学习java的小伙伴们有非常好的帮助,需要的朋友可以参考下
    2021-04-04
  • SpringBoot 如何编写配置文件

    SpringBoot 如何编写配置文件

    这篇文章主要介绍了SpringBoot 编写配置文件的两种方法,帮助大家更好的理解和使用springboot框架,感兴趣的朋友可以了解下
    2020-11-11
  • Mybatis中的自定义映射resultMap

    Mybatis中的自定义映射resultMap

    在MyBatis中,自定义映射resultMap可以让你精确控制如何将数据库返回的结果集映射到Java对象上,本文给介绍了Mybatis之自定义映射resultMap,需要的朋友可以参考下
    2024-03-03

最新评论