Domanda

Ho una pagina che attualmente sta utilizzando il microformato datetime per visualizzare un timestamp , ma ho mostrato solo l'ora leggibile dall'uomo per il mio fuso orario:

<abbr class="published" title="2009-01-09T09:16:00-05:00">
Friday, January 9, 2009 at 9:16 am (EST)</abbr>

Quello che mi piacerebbe fare è riscrivere innerHTML affinché il tag abbr sia dello stesso formato, ma nel fuso orario locale dell'utente. Quindi per un lettore di Seattle, quanto sopra dovrebbe essere convertito in:

<abbr class="published" title="2009-01-09T09:16:00-05:00">
Friday, January 9, 2009 at 6:16 am (PST)</abbr>

Ho esaminato Oggetto data Javascript , che mi consente di ottenere la differenza di fuso orario locale. Ma ho alcuni problemi:

  1. Non vedo un modo semplice per creare un nuovo oggetto Date da un ISO- 8601 data e ora. (Suppongo che potrei analizzare con sottostringhe o regex se non c'è modo più veloce.)

  2. Non vedo un modo per ottenere l'abbreviazione denominata per il fuso orario. Ad esempio, per un lettore di Seattle, vorrei che il tempo avesse "PST" " aggiunto alla fine, altrimenti non è chiaro a quell'utente che il timestamp è stato convertito (specialmente se è un visitatore frequente e si è abituato al fatto che i miei tempi sono in EST).

È stato utile?

Soluzione

Ecco il mio codice che analizza un timestamp ISO:

function isoDateStringToDate (datestr) {
  if (! this.re) {
    // The date in YYYY-MM-DD or YYYYMMDD format
    var datere = "(\\d{4})-?(\\d{2})-?(\\d{2})";
    // The time in HH:MM:SS[.uuuu] or HHMMSS[.uuuu] format
    var timere = "(\\d{2}):?(\\d{2}):?(\\d{2}(?:\\.\\d+)?)";
    // The timezone as Z or in +HH[:MM] or -HH[:MM] format
    var tzre = "(Z|(?:\\+|-)\\d{2}(?:\\:\\d{2})?)?";
    this.re = new RegExp("^" + datere + "[ T]" + timere + tzre + "<*>quot;);
  }

  var matches = this.re.exec(datestr);
  if (! matches)
    return null;

  var year = matches[1];
  var month = matches[2] - 1;
  var day = matches[3];
  var hour = matches[4];
  var minute = matches[5];
  var second = Math.floor(matches[6]);
  var ms = matches[6] - second;
  var tz = matches[7];
  var ms = 0;
  var offset = 0;

  if (tz && tz != "Z") {
    var tzmatches = tz.match(/^(\+|-)(\d{2})(\:(\d{2}))$/);
    if (tzmatches) {
      offset = Number(tzmatches[2]) * 60 + Number(tzmatches[4]);
      if (tzmatches[1] == "-")
        offset = -offset;
    }
  }

  offset *= 60 * 1000;
  var dateval = Date.UTC(year, month, day, hour, minute, second, ms) - offset;

  return new Date(dateval);
}

Sfortunatamente, non gestisce neanche le abbreviazioni del fuso orario. Dovresti modificare " tzre " espressione per accettare lettere e l'unica soluzione che conosco per gestire le abbreviazioni del fuso orario in Javascript è quella di avere una tabella di consultazione che si aggiorna manualmente in caso di modifiche alle ore di ora legale regionali.

Altri suggerimenti

EcmaScript ha formalizzato l'aggiunta di una stringa di stile ISO-8601 come imput per una data JavaScript. Poiché la maggior parte delle implementazioni JS non supporta questo, ho creato un wrapper per l'oggetto Date, che ha questa funzionalità. Se imposti i tag del titolo per l'output in offset UTC / GMT / Z / Zulu, puoi usare my Estensioni EcmaScript 5 per l'oggetto Date di JS .

Per i valori DateTime che devono essere utilizzati negli script lato client, in genere cerco di fare sempre quanto segue. Memorizza data + ora nella zona UTC (anche nei database). Trasmettere le date-ora nella zona UTC. Da client a server, è possibile utilizzare il metodo .toISOString () nel collegamento sopra. Dal server al client questo è relativamente semplice.

Via jQuery (con estensione):

$('.published').each(function(){
  var dtm = new Date(this.title);
  if (!isNaN(dtm)) {
    this.text(dtm.toString());
  }
});

Non ricordo se ho aggiunto il supporto per date-time non utc nell'input, ma non sarebbe troppo difficile renderne conto.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top