web-dev-qa-db-fra.com

Parse date sans fuseau horaire javascript

Je veux analyser la date sans fuseau horaire en JavaScript. J'ai essayé:

new Date(Date.parse("2005-07-08T00:00:00+0000"));

Retours Vendredi 08 juillet 2005 02:00:00 GMT + 0200 (Heure avancée d'Europe centrale)

new Date(Date.parse("2005-07-08 00:00:00 GMT+0000"));

Renvoie le même résultat

new Date(Date.parse("2005-07-08 00:00:00 GMT-0000"));

Renvoie le même résultat

Je veux analyser le temps:

  1. Sans fuseau horaire.

  2. Sans appeler le constructeur Date.UTC ou la nouvelle date (année, mois, jour).

  3. Juste une simple chaîne de caractères dans le constructeur Date (sans approches de prototype).

  4. Je dois produire un objet Date et non pas String.

95
Athlan

La date est analysée correctement, c’est juste toString qui la convertit dans votre fuseau horaire local:

> new Date(Date.parse("2005-07-08T11:22:33+0000"))
Fri Jul 08 2005 13:22:33 GMT+0200 (CEST)
> new Date(Date.parse("2005-07-08T11:22:33+0000")).toUTCString()
"Fri, 08 Jul 2005 11:22:33 GMT"

Les objets Date en Javascript sont des horodatages - ils ne contiennent qu'un nombre de millisecondes depuis l'époque. Il n'y a pas d'informations de fuseau horaire dans un objet Date. La date de calendrier (jour, minutes, secondes) que cet horodatage représente est une question d’interprétation (une des méthodes to...String). 

L'exemple ci-dessus montre que la date est correctement analysée, c'est-à-dire qu'elle contient en réalité une quantité de millisecondes correspondant à "2005-07-08T11: 22: 33" en GMT.

75
georg

J'ai le même problème. Je reçois une date sous forme de chaîne, par exemple: '2016-08-25T00: 00: 00', mais je dois disposer de l'objet Date avec l'heure exacte. Pour convertir String en objet, j'utilise getTimezoneOffset:

var date = new Date('2016-08-25T00:00:00')
var userTimezoneOffset = date.getTimezoneOffset() * 60000;
new Date(date.getTime() - userTimezoneOffset);

getTimezoneOffset() retournera une valeur négative ou positive pour l'éther. Ceci doit être soustrait pour fonctionner dans tous les endroits du monde.

72
wawka

J'ai rencontré le même problème et je me suis souvenu de quelque chose d'inquiétant à propos d'un projet hérité sur lequel je travaillais et de la façon dont ils ont géré ce problème. Je ne le comprenais pas à ce moment-là et je m'en fichais bien avant d'avoir moi-même rencontré le problème

var date = '2014-01-02T00:00:00.000Z'
date = date.substring(0,10).split('-')
date = date[1] + '-' + date[2] + '-' + date[0]

new Date(date) #Thu Jan 02 2014 00:00:00 GMT-0600

Quelle que soit la raison, la date indiquée sous '01-02-2014 'définit le fuseau horaire sur zéro et ignore le fuseau horaire de l'utilisateur. Cela peut être un coup de chance dans la classe Date, mais cela existait il y a longtemps et existe encore de nos jours. Et cela semble fonctionner sur plusieurs navigateurs. Essayez par vous-même.

Ce code est implémenté dans un projet global où les fuseaux horaires sont très importants mais la personne qui regarde la date ne se souciait pas du moment exact où elle avait été introduite.

10
Iwnnay

L'objet Date lui-même contiendra quand même un fuseau horaire et le résultat renvoyé aura pour effet de le convertir en chaîne de manière par défaut. C'est à dire. vous ne pouvez pas créer un objet de date sans fuseau horaire. Mais ce que vous pouvez faire est d’imiter le comportement de l’objet Date en créant votre propre objet . C’est toutefois préférable d’être remis à des bibliothèques comme moment.js .

5
mishik

solution simple

const handler1 = {
  construct(target, args) {
    let newDate = new target(...args);
    var tzDifference = newDate.getTimezoneOffset();
    return new target(newDate.getTime() + tzDifference * 60 * 1000);
  }
};

Date = new Proxy(Date, handler1);
2
alexey

Juste une note générique. un moyen de rester flexible. 

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Nous pouvons utiliser getMinutes (), mais il ne renvoie qu'un seul nombre pendant les 9 premières minutes.

let Epoch = new Date() // Or any unix timestamp

let za = new Date(Epoch),
    zaR = za.getUTCFullYear(),
    zaMth = za.getUTCMonth(),
    zaDs = za.getUTCDate(),
    zaTm = za.toTimeString().substr(0,5);

console.log(zaR +"-" + zaMth + "-" + zaDs, zaTm)

Date.prototype.getDate()
    Returns the day of the month (1-31) for the specified date according to local time.
Date.prototype.getDay()
    Returns the day of the week (0-6) for the specified date according to local time.
Date.prototype.getFullYear()
    Returns the year (4 digits for 4-digit years) of the specified date according to local time.
Date.prototype.getHours()
    Returns the hour (0-23) in the specified date according to local time.
Date.prototype.getMilliseconds()
    Returns the milliseconds (0-999) in the specified date according to local time.
Date.prototype.getMinutes()
    Returns the minutes (0-59) in the specified date according to local time.
Date.prototype.getMonth()
    Returns the month (0-11) in the specified date according to local time.
Date.prototype.getSeconds()
    Returns the seconds (0-59) in the specified date according to local time.
Date.prototype.getTime()
    Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC (negative for prior times).
Date.prototype.getTimezoneOffset()
    Returns the time-zone offset in minutes for the current locale.
Date.prototype.getUTCDate()
    Returns the day (date) of the month (1-31) in the specified date according to universal time.
Date.prototype.getUTCDay()
    Returns the day of the week (0-6) in the specified date according to universal time.
Date.prototype.getUTCFullYear()
    Returns the year (4 digits for 4-digit years) in the specified date according to universal time.
Date.prototype.getUTCHours()
    Returns the hours (0-23) in the specified date according to universal time.
Date.prototype.getUTCMilliseconds()
    Returns the milliseconds (0-999) in the specified date according to universal time.
Date.prototype.getUTCMinutes()
    Returns the minutes (0-59) in the specified date according to universal time.
Date.prototype.getUTCMonth()
    Returns the month (0-11) in the specified date according to universal time.
Date.prototype.getUTCSeconds()
    Returns the seconds (0-59) in the specified date according to universal time.
Date.prototype.getYear()
    Returns the year (usually 2-3 digits) in the specified date according to local time. Use getFullYear() instead. 
0
Cryptopat