Reputation: 2923
In my jersey rest api when a user sends a POST request
{
"user":"john",
"question":"what was temperature an hour ago"
}
a QuestionProcessor
transforms the String an hour ago
into LocalDateTime.now(ZoneId.of(UTC)).minusHours(5).format(dateformatter);
I want to replace the UTC
default by the users timezone. How can I do that?
Thanks for the help
Upvotes: 1
Views: 1435
Reputation: 339502
You asked:
replace the UTC default by the users timezone
Easy:
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime now = ZonedDateTime.now( z ) ;
ZonedDateTime then = now.minusHours( 1 ) ;
The catch: You must know the user’s time zone name such as Africa/Tunis
, Europe/Paris
, Asia/Kolkata
, Pacific/Auckland
, or America/Montreal
.
You need to reformulate your REST API to also pass a field for time zone name.
Specify a proper time zone name in the format of Continent/Region
, such as examples seen above. Never use the 2-4 letter abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
By the way, I cannot imagine when calling LocalDateTime.now
is the right thing to do. That class cannot represent a moment as it purposely lacks the context of an offset-from-UTC or time zone. Use Instant
, OffsetDateTime
, or ZonedDateTime
instead.
Upvotes: 4