Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve the client (browser) timezone in Vaadin Flow?

I need to determine the browser timezone. I tried to follow this post but does not work (Vaadin 20). Here is my code:

    ZoneId myZoneId;
    ...

    UI.getCurrent().getPage().retrieveExtendedClientDetails(extendedClientDetails -> {
      myZoneId = ZoneId.of(extendedClientDetails.getTimeZoneId());
    });

    // here myZoneId has value null.

So I tried to do it myself, initially simply displaying it.

    UI.getCurrent().getPage()
            .executeJs("return Intl.DateTimeFormat().resolvedOptions().timeZone;")
            .then(value -> Notification.show(value.asString()));

It works and I read "Europe/Rome", but its value does not seem something that I can map to a ZoneId in Java.

I could explore a little more the Javascript zone object but I also was unable to find where my code actually went to debug it with chrome debugger (there is no mention in Vaadin doc where the code goes).

I could work on the returned value and try to interpret it but I would like to avoid reinventing the wheel.

Do anybody has any code that works?

like image 729
Franco G Avatar asked Oct 18 '25 07:10

Franco G


1 Answers

retrieveExtendedClientDetails is an asynchronous call, thus the result is available inside the callback and not right after firing the callback (on the place you commented).

Also, UI.getCurrent() could return null if called too soon, f.e. in a constructor.

retrieveExtendedClientDetails makes a client roundtrip the first time it is run (docs).

If already obtained, the callback is called directly. Otherwise, a client-side roundtrip will be carried out.

That means you could try to run it when initialising the UI and later you should have it ready right away after firing.

@SpringComponent
public class MyVaadinServiceInitListener implements VaadinServiceInitListener {
    @Override
    public void serviceInit(ServiceInitEvent event) {
        event.getSource().addUIInitListener(uiEvent -> {   
            var ui = event.getUI();
            ui.getPage().retrieveExtendedClientDetails(detail -> {});
        });
    }    
}

Another solution is to read the zone inside the callback.

like image 115
Hawk Avatar answered Oct 21 '25 00:10

Hawk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!