英文:
How to convert LocalDate.now() to CEST/CET LocalDate.now()?
问题
我正在创建一个新的REST服务,该服务消耗另一个服务。在每个请求中,我必须包含当前日期,并且当前日期不能是过去的日期。
我正在使用 LocalDate.now()
来获取当前日期。
问题是我不知道我的终端用户所在的时区,而我需要以CEST时区调用后端服务。
由于CEST比UTC快2小时,如果用户在例如8月9日23:00发送了一个新请求,请求将命中后端服务的日期为8月9日,但日期将为8月10日01:00。
如何将 LocalDate.now()
转换为CEST/CET的 LocalDate.now()
?
英文:
I am creating a new REST service which consumes another service. With every request i have to include the current date, and that current date must not be in the past.
I am using LocalDate.now()
to get the current date
The problem is that i dont know the time zone of my end users, and i to call the backend service with CEST time zone
Because of the CEST is +2 to the UTC, if the user sent a new request at fx 9 AUG 23:00, the request will hit the backend service with date 9 AUG, but the day will be 10 AUG 01:00
How to convert LocalDate.now() to CEST/CET LocalDate.now()?
答案1
得分: 4
没有办法从HTTP请求中找到用户的时区。例如,参考以下链接:
- https://stackoverflow.com/questions/3001260/how-to-detect-the-timezone-of-a-client
- https://stackoverflow.com/questions/6091804/is-there-another-way-to-get-a-users-time-zone-from-a-httpservletrequest-object
一种解决方案是将用户首选的时区存储在用户的个人资料中,就像存储姓名、电子邮件地址和其他信息一样。另一种解决方案是在客户端代码中找到时区并将其作为请求参数传递。第三种解决方案(最不可靠的)是通过地理定位用户的IP地址。
一旦找到时区,就可以轻松找到该时区中的LocalDate
:
String userTimeZone = "Europe/Paris";
LocalDate userLocalDate = LocalDate.now(ZoneId.of(userTimeZone));
英文:
There is no way to find the user's time zone from a HTTP request: see for example
- https://stackoverflow.com/questions/3001260/how-to-detect-the-timezone-of-a-client
- https://stackoverflow.com/questions/6091804/is-there-another-way-to-get-a-users-time-zone-from-a-httpservletrequest-object
One solution is to store the user's preferred time zone in the user's profile the same way you store name, email address and other things. Another solution is to find the time zone in client-side code and pass it in as a request parameter. A third solution (the least reliable) is to geolocate the user's IP address.
Once you do find the time zone, finding the LocalDate
in that zone is easy:
String userTimeZone = "Europe/Paris";
LocalDate userLocalDate = LocalDate.now(ZoneId.of(userTimeZone));
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论