'How can we dynamically change the timezone in java rest api response?

We have api: call_summary/

{
  "id": 2,
  "number: "xyz",
  "call_time": "2021-10-11T03:50:23Z"
}

We have multiple users with various timezones like ADT, EDT, IST, etc. When users access this API the call_time should change according to user timezone. I tried to use @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "IST"), but this won't allow us to change the call_time dynamically. Is there any way to do it using annotations or filters?



Solution 1:[1]

I would recommend storing call_time in two columns, UTC and users local time-zone.

By doing so, it will eliminate complexity and confusion at both ends (server and client)

Solution 2:[2]

Check the following link, it may help you: Pass browser timezone to the backend springboot application to generate reports with dates as per the browser timezone. According to the latter, you can use TimeZone as input to your controller. You could do something like the following:

@RestController
public class TestController {
  DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

  @GetMapping(value = "/test")
  public String generate(TimeZone timezone) throws IOException {
    return LocalDateTime.now().atZone(timezone.toZoneId()).format(formatter);
  }
}

Alternatively, you could get the timezone from HttpServletRequest.

Solution 3:[3]

JSON Serialize is the best fit for this custom data conversion as per user or user role. I created the converter class and called by @JsonSerialize(converter = LocalDateTimeToStringConverter.class) and @JsonDeserialize(converter = StringToLocalDatetimeConverter.class). It worked as per my expection.

For reference, I attached the sample link below.

Custom conversion using JSON-Serialize-Deserialize

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Umais Gillani
Solution 2 dchar
Solution 3 Jyoti Singh