Home > Back-end >  How can we dynamically change the timezone in java rest api response?
How can we dynamically change the timezone in java rest api response?

Time:10-11

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?

CodePudding user response:

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)

CodePudding user response:

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.

  • Related