是often recommended日期时间以 UTC 格式存储在数据库中,并以本地时区显示给用户/从用户那里接收。
我正在尝试在 Spring MVC/Spring Boot 应用程序中实现此模式,但无法找到文档或示例。我在 @ModelAttribute 表单对象的 java.util.Date 属性上使用 @DateTimeFormat 注释来进行 Spring 解析/格式化日期。
Spring 是否内置了对这种模式的支持?类似于 Django's timezone-aware datetimes 的内容会很好。如果没有,是否有一种不太麻烦的实现方式?或者是否有更好的方法在 Spring MVC 应用程序中处理/存储日期时间?
目前该应用程序仅适用于英国,因此目前我只需要支持 BST(夏令时),而不是针对不同用户的不同时区。然而,支持不同时区的用户是 future 的潜在需求。
最佳答案
希望这对您有所帮助,或者至少是您可以开始的地方。
看起来最好的方法是使用 OffsetDateTime 类型来存储日期。将来自用户的 dateTime 值转换为 UTC 很容易:
OffsetDateTime createdOn = requestDto.getCreatedOn();
OffsetDateTime utc = createdOn.atZoneSameInstant(ZoneId.of("UTC"));
再回来(当然你也需要存储用户时区):
OffestDateTime eventDate = modelObject.getEventDate();
OffsetDateTime userTime = eventDate.atZoneSameInstant(ZoneId.of(userTimeZone));
要在 UTC 中实例化新的日期对象,您可以使用 clock-object:
OffestDateTime now = OffestDateTime.now(Clock.systemUTC());
ModelObject dto = new ModelObject();
dto.setEventDate(now);
最后,如果您不需要显示偏移量,您可以使用 LocalDateTime 类型:
OffestDateTime eventDate = databaseModelObject.getEventDate();
LocalDateTime userTime = eventDate.atZoneSameInstant(ZoneId.of(userTimeZone)).toLocalDateTime());
ResponseDto response = new ResponseDto();
response.setEventDate(userTime);
关于java - Spring MVC - 将日期从用户时区转换为 UTC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33735757/