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

后端 未结 5 1088
佛祖请我去吃肉
佛祖请我去吃肉 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:35

    When I used this, I had to change the line

    var hours = givenDate.getHours();
    

    to

    var hours = givenDate.getUTCHours();
    

    When debugging through this, the line var givenDate = new Date(tagText) ends up creating a Date object that is in UTC (if you give it a date in RFC1123 format, e.g. ffffd, dd MMM yyyy HH:mm:ss GMT), but when you call getHours on that you get the hours in the local time zone. So unless you call getUTCHours, it doesn't work.

    So the full thing is

    /*
        Note: this requires that the JQuery-DateFormat plugin 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.getUTCHours();
                hours += offset;
                givenDate.setHours(hours);
    
                // format the date
                var localDateString = $.format.date(givenDate, format);
                $(this).html(localDateString);
            });
        };
    })(jQuery);
    

    See this other question for how I used it in combination with the timeago plugin.

提交回复
热议问题