Cuando he usado esto, he tenido que cambiar la línea
var hours = givenDate.getHours();
a
var hours = givenDate.getUTCHours();
Al depurar a través de este, la línea var givenDate = new Date(tagText)
termina por crear un objeto Date que es en UTC (si le das una fecha en formato RFC1123, por ejemplo, ddd, dd MMM yyyy HH:mm:ss GMT
), pero cuando llamas a getHours, obtienes las horas en la zona horaria local. Entonces, a menos que llame a getUTCHours, no funciona.
Así que lo más completa es
/*
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);
Ver this other question de como lo he usado en combinación con el plugin timeago.
tuve que modificar algunas cosas utilizando su código y jQuery. Puede ver todos los detalles en mi blog: [http://emplementation.blogspot.com/2010/11/displaying-timestamps-in-clientsviewers.html](http://emplementation.blogspot.com/2010/11/ displaying-timestamps-in-clientsviewers.html) – docchang
Las zonas horarias no siempre se encuentran en límites de una hora, por lo que debe aplicar el desplazamiento en minutos, no en horas.Por ejemplo, [Venezuela es UTC-04: 30] (https://en.wikipedia.org/wiki/UTC%E2%88%9204:30) – jwadsack