0

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()?

Melad Basilius
  • 3,847
  • 10
  • 44
  • 81
  • `LocalDate.now(ZoneOffset.ofHours(2))`? – Sweeper Aug 13 '20 at 10:14
  • 1
    @Sweeper, what if the end users are from different time zones ? – Melad Basilius Aug 13 '20 at 10:18
  • 1
    Will you still be converting to CEST in December? If not, it may be worth using a more specific zone, e.g. `Europe/Berlin`. – Andy Turner Aug 13 '20 at 10:18
  • How is that date being used? Why must the date not be in the past? And why do you have to send a LocalDate (which by definition is relative to where you are) instead of an absolute, timezone-independent Instant? How about sending tomorrow's date? That will never be in the past for anyone. – Thilo Aug 13 '20 at 10:20
  • 2
    How is _that current date must not be in the past_ determined? – Glains Aug 13 '20 at 10:21
  • When you make sure that the date is not in the past, a few milliseconds later it may nevertheless be in the past. I don’t really get what you are trying to obtain. – Ole V.V. Aug 13 '20 at 15:53

1 Answers1

4

There is no way to find the user's time zone from a HTTP request: see for example

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));
Joni
  • 108,737
  • 14
  • 143
  • 193