Display date/time in user's locale format and

2019-01-01 00:07发布

I want the server to always serve dates in UTC in the HTML, and have JavaScript on the client site convert it to the user's local timezone.

Bonus if I can output in the user's locale date format.

14条回答
谁念西风独自凉
2楼-- · 2019-01-01 01:02

getTimeZoneOffset() and toLocaleString are good for basic date work, but if you need real timezone support, look at mde's TimeZone.js.

There's a few more options discussed in the answer to this question

查看更多
初与友歌
3楼-- · 2019-01-01 01:03

Once you have your date object constructed, here's a snippet for the conversion:

The function takes a UTC formatted Date object and format string.
You will need a Date.strftime prototype.

function UTCToLocalTimeString(d, format) {
    if (timeOffsetInHours == null) {
        timeOffsetInHours = (new Date().getTimezoneOffset()/60) * (-1);
    }
    d.setHours(d.getHours() + timeOffsetInHours);

    return d.strftime(format);
}
查看更多
登录 后发表回答