使用LocalDateTime进行Java日期和时间操作,带有时区。

huangapple go评论72阅读模式
英文:

Java date and time manipulation with zone using LocalDateTime

问题

我正在开发一个Spring Boot应用,一些实体中有一些日期/时间字段。考虑到这个应用将被来自世界各地的多个用户使用,日期和时间字段应该被适当处理,我正在尝试遵循其中一个正确的方法。

在这种情况下,你会建议如何保存来自不同时区的用户的日期和时间。我想到了以下几种方法:

  • 我可以基于UTC+0保存日期和时间,然后当其他人检索数据时,可以根据他们当前的时区显示给他们。

  • 或者根据用户的本地时间保存日期和时间,使用其本地时区。

我对这个问题感到很困惑,因为我之前没有经验。就我所见,我可以使用Java 11+的java.time中的LocalDateTime。但如果你有比java.time更好的建议,也可以分享一下。

英文:

I am developing a Spring Boot app and there are some date/time fields in some entities. When considering an application will be used by multiple users from all around the world, the date and time fields should be treated properly and I am trying to follow one of the proper approach.

In this scene, what would you suggest to save date and time by users from different time zones. I think the following approaches:

  • I can save date and time based on UTC+0 and then when someone else retrieve data, I can show them based on their current time zone.

  • or save date and time based on the local time of the user with that local time zone.

I am really confused with this issue as I have no previous experience. And as far as I see, I can use LocalDateTime of java.time with Java 11+. But if you have another suggestion that is better than java.time, you can share also.

答案1

得分: 1

我强烈推荐使用ZonedDateTime对象,它包含有关日期、时间和相关时区的信息。随着引入Java 8的Java日期和时间API,很容易进行日期、时间、时区的转换和计算。要直接存储这些对象,请参考您正在使用的数据库抽象层。如果需要,您可以使用DateTimeFormatter轻松创建String表示以便查看和存储。

如果您需要更详细的答案,请提供更详细的问题,最好附带示例代码。

英文:

I highly recommend using the ZonedDateTime object which holds information about the date, the time, and the regarding timezone. With the Java Date and Time API introduced with Java 8 it is very easy to convert dates, times, zones, and to calculate with them. To store these objects directly, refer to your database abstraction layer you are using. If needed, you can use the DateTimeFormatter to create String representations easily to view and store.

If you need a more detailed answer, please provide a more detailed question, preferably with example code.

答案2

得分: 0

我会选择第一种解决方案,并根据客户的时区提供时间。请注意,您显示的本地时区将是客户端调用的服务器的时区。要获取客户端的真实时区,确保从客户端本身获取。也许这个链接可能有帮助。

英文:

I will go for the first solution and give the client the time based on his/her zone. Keep in mind that the local time zone that you will display will be the time zone of the server which the client has called. To get the real time zone of the client you need to make sure to get it from the client itself. May be this link could help

huangapple
  • 本文由 发表于 2023年2月18日 18:18:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75492653.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定