Is there a JQuery plugin to convert UTC datetimes to local user timezone?

后端 未结 5 1095
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-05 05:23

If I have a tag:

2010-01-01 11:30 PM

I would like a jquery script or plug in to convert every <

5条回答
  •  悲&欢浪女
    2020-12-05 05:48

    Ok, so I created one that does it:

    /*
        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);
    

    Usage:

        2/5/2010 10:30 PM
    
        $('.utcdate').localTimeFromUTC('MM/dd/yyyy hh:mm a');
    

提交回复
热议问题