How to get user’s ZoneId in Vaadin

Actually, the task can be split in two subtasks:
— retrieving offset in the form which Vaadin can provide (integer number of milliseconds);
— formatting it so that we could construct ZoneId.

The first part can be handled with:

int offsetInt = getUI().getPage().getWebBrowser().getTimezoneOffset();

The second part can be handled this way:

    private static final int MILLISECONDS_IN_HOUR = 3_600_000;
    private static final int MILLISECONDS_IN_MINUTE = 60000;
    private static final int SECONDS_IN_MINUTE = 60;
...
        String offset = String.format("%02d:%02d",
                Math.abs(offsetInt / MILLISECONDS_IN_HOUR),
                Math.abs((offsetInt / MILLISECONDS_IN_MINUTE) % SECONDS_IN_MINUTE));
        offset = (offsetInt >= 0 ? "+" : "-") + offset;
        ZoneId zoneId = ZoneId.of(offset);

So, for offset -85*3600*100 milliseconds (-8.5 hours) you are supposed to get «-08:30» which is compliant with ZoneId.of() method.

You can leave a response, or trackback from your own site.

Leave a Reply