admin管理员组

文章数量:1291616

I'm sending the user's timezone from frontend in a cookie like this:

document.addEventListener("DOMContentLoaded", () => {
    const currentTZ = Intl.DateTimeFormat().resolvedOptions().timeZone;
    const cookies = document.cookie.split("; ").reduce((acc, cookie) => {
        const [key, value] = cookie.split("=");
        acc[key] = value;
        return acc;
    }, {});

    if (!cookies["COOKIE.TZ"]) {
        document.cookie = `COOKIE.TZ=${currentTZ}; path=/`;

        fetch(`/?zone=${encodeURIComponent(currentTZ)}`, {
            method: "GET",
        });
    } else if (cookies["COOKIE.TZ"] !== currentTZ) {
        document.cookie = `COOKIE.TZ=${currentTZ}; path=/`;

        fetch(`/?zone=${encodeURIComponent(currentTZ)}`, {
            method: "GET",
        });
    }
});

I want the date to automatically convert to the user's time zone because I now put it in the GlobalControllerAdvice

@ModelAttribute("userZoneId")
    public ZoneId getUserZoneId(HttpServletRequest request) {
        String timeZoneId = getCookieValue(request, "COOKIE.TZ");
        return (timeZoneId != null) ? ZoneId.of(timeZoneId) : ZoneId.of("Europe/Moscow");
    }

    private String getCookieValue(HttpServletRequest request, String name) {
        if (request.getCookies() != null) {
            for (Cookie cookie : request.getCookies()) {
                if (cookie.getName().equals(name)) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

and then I use it explicitly

<td th:text="${#temporals.format(user.dateCreated, 'dd-MM-yyyy HH:mm', userZoneId)}"></td>

and it works, but I want to automatically convert to timezone and print only:

<td th:text="${#temporals.format(user.dateCreated, 'dd-MM-yyyy HH:mm')}"></td>

Without using GlobalControllerAdvice. Where to specify and save time zone?

本文标签: springWhere should I store the user39s timezoneStack Overflow