是否有一个JQuery插件将UTC日期时间转换为本地用户时区?

Cod*_*rue 20 datetime jquery-plugins

如果我有一个标签:

<span class="utctime">2010-01-01 11:30 PM</span>
Run Code Online (Sandbox Code Playgroud)

我想要一个jquery脚本或插件将每个utctime类转换为当前用户的浏览器本地时间.在写一篇文章之前我更愿意找到它.

Cod*_*rue 17

好的,所以我创建了一个:

/*
    Note: this requires that the JQuery-DateFormat plugin (available here) be loaded first
    http://plugins.jquery.com/project/jquery-dateFormat
*/

(function ($) {
    $.fn.localTimeFromUTC = function (format) {

        return this.each(function () {

            // get time offset from browser
            var currentDate = new Date();
            var offset = -(currentDate.getTimezoneOffset() / 60);

            // get provided date
            var tagText = $(this).html();
            var givenDate = new Date(tagText);

            // apply offset
            var hours = givenDate.getHours();
            hours += offset;
            givenDate.setHours(hours);

            // format the date
            var localDateString = $.format.date(givenDate, format);
            $(this).html(localDateString);
        });
    };
})(jQuery);
Run Code Online (Sandbox Code Playgroud)

用法:

    <span class="utcdate">2/5/2010 10:30 PM</span>

    $('.utcdate').localTimeFromUTC('MM/dd/yyyy hh:mm a');
Run Code Online (Sandbox Code Playgroud)


小智 7

使用输入日期查找时区偏移量.对于DST更改很重要.

(function ($) {
$.fn.localTimeFromUTC = function (format) {
    return this.each(function () {

        // get provided date 
        var tagText = $(this).html();
        var givenDate = new Date(tagText);

        if(givenDate == 'NaN') return;

        // get time offset from browser 
        var offset = -(givenDate.getTimezoneOffset() / 60);

        // apply offset 
        var hours = givenDate.getHours();
        hours += offset;
        givenDate.setHours(hours);

        // format the date 
        var localDateString = $.format.date(givenDate, format);
        $(this).html(localDateString);


    });
};
})(jQuery); 
Run Code Online (Sandbox Code Playgroud)

像......一样使用它

function ConvertDatesToLocalTime() {
        $('.ConvertUtcToLocal').localTimeFromUTC('MM/dd/yyyy hh:mm:ss a');
    }

    $(document).ready(function () {
        ConvertDatesToLocalTime();

    });
Run Code Online (Sandbox Code Playgroud)

将"ConvertUtcToLocal"类分配给需要转换的所有元素.