Quando ho usato questo, ho dovuto cambiare la linea
var hours = givenDate.getHours();
a
var hours = givenDate.getUTCHours();
Quando il debug attraverso questa, la linea var givenDate = new Date(tagText)
finisce per creare un oggetto Date che è in UTC (se gli dai una data nel formato RFC1123, ad es. ddd, dd MMM yyyy HH:mm:ss GMT
), ma quando chiami getHours su ciò ottieni le ore nel fuso orario locale. Quindi, a meno che non chiami getUTCHours, non funziona.
Quindi la cosa è piena
/*
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);
Vedi this other question per come l'ho usato in combinazione con il plugin timeago.
ho dovuto modificare un paio di cose usando il codice e jQuery. Puoi vedere tutti i dettagli sul mio blog: [http://emplementation.blogspot.com/2010/11/displaying-timestamps-in-clientsviewers.html](http://emplementation.blogspot.com/2010/11/ display-timestamps-in-clientsviewers.html) – docchang
I fusi orari non sono sempre su un limite di un'ora quindi è necessario applicare l'offset a minuti, non ore.Ad esempio, [Venezuela è UTC-04: 30] (https://en.wikipedia.org/wiki/UTC%E2%88%9204:30) – jwadsack