2010-09-30 14 views

Respuesta

17

Ok, así que creé una que lo hace:

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

Uso:

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

    $('.utcdate').localTimeFromUTC('MM/dd/yyyy hh:mm a'); 
+0

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

+0

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

0

CodeGrue gracias por compartir esto con la comunidad.

Para aquellos que se ven obligados a trabajar con otras zonas horarias que UTC .. Usted puede alterar la función mediante la adición de la diferencia de tiempo de la siguiente manera:

fragmento original:

var offset = -(currentDate.getTimezoneOffset()/60); 

de fragmentos alterados para trabajar con CEST zona horaria (zona horaria offset: UTC + 2 horas):

var offset = -(currentDate.getTimezoneOffset()/60 + 2); 

y así sucesivamente.

0

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.

+0

en realidad, usted necesita el getHours y no getUtcHour, que hará el shift, porque su fecha ya está en utc (el objetivo es mostrar local) para que funcione la primera versión pero no la suya – tahir

7

Use la fecha de entrada para buscar el desplazamiento de la zona horaria. Importante para los cambios de horario de verano.

(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); 

Se usa como ....

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

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

    }); 

clase Asignar 'ConvertUtcToLocal' a todos los elementos que requieren conversión.

+0

Elaboración de la referencia del horario de verano, si el UTC que se está convirtiendo proviene de una fecha que estaba en horario de verano, y hoy NO está en horario de verano, a continuación, basar su desplazamiento en la fecha de hoy devolverá un tiempo que está desactivado por una hora. –

+0

Dice "No se puede leer la propiedad 'fecha' de indefinido" en la línea $ .format.date (givenDate, format) ;. Me estoy perdiendo de algo ? – Dashrath

+0

He resuelto el problema incluyendo jquery-dateFormat.js en la página de https://github.com/phstc/jquery-dateFormat – Dashrath

1
$(".localdatetime").each(function() { 
     var datestr = $(this).text(); 
     //alert(datestr); 
     if (datestr.trim() != '') { 
      var dateOb = (new Date(Date.parse(datestr, 'MM-dd-yyyy HH:mm'))).setTimezone("GMT").toString('dd MMM yyyy hh:mm tt'); 
      //alert(dateOb); 
      $(this).text(dateOb); 
     } 
    }) 

esto también se puede utilizar junto con la biblioteca Date.js para mostrar la hora en la zona horaria del usuario

Cuestiones relacionadas