2010-09-30 14 views

risposta

17

Ok, così ho creato uno che lo fa:

/* 
    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:

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

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

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

+0

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

0

CodeGrue grazie mille per aver condiviso questo con la comunità.

Per coloro che sono costretti a lavorare con altri fusi orari rispetto a UTC .. si può alterare la funzione aggiungendo la differenza di tempo in questo modo:

frammento originale:

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

Snippet alterata a lavorare con Fuso orario CEST (Fuso orario fuso: UTC + 2 ore):

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

e così via.

0

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.

+0

in realtà, è necessario il getHours e non getUtcHour, che eseguirà il MAIUSC, perché la tua data è già in UTC (lo scopo è di visualizzare locale) quindi la prima versione funziona ma non la tua – tahir

7

Utilizzare la data di inserimento per trovare l'offset del fuso orario. Importante per le modifiche all'ora legale.

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

Usalo come ....

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

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

    }); 

Assegna 'ConvertUtcToLocal' di classe a tutti gli elementi che richiedono la conversione.

+0

Elaborazione del riferimento di ora legale, se l'UTC in fase di conversione proviene da una data che era in DST e oggi NON è in ora legale, quindi basare l'offset sulla data di oggi restituirà un orario disattivato di un'ora. –

+0

Dice "Impossibile leggere la proprietà 'data' di undefined" on line $ .format.date (givenDate, format) ;. mi sto perdendo qualcosa ? – Dashrath

+0

Ho risolto il problema includendo jquery-dateFormat.js nella pagina 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); 
     } 
    }) 

questo può essere utilizzato anche insieme con la biblioteca Date.js per visualizzare l'ora nel fuso orario dell'utente

Problemi correlati