1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| // Pour communiquer une date et une heure précise il faut la construire en UTC :
// Pour le 2014-08-08 à 11:45:20 et 375 millisecondes.
var dt = new Date( Date.UTC( 2014, 7, 8, 11, 45, 20, 375 ) );
// Avec la méthode toLocaleString() chacun, sur son ordinateur, où qu'il soit
// dans le monde aura l'heure locale qui correspond à ce moment en UTC.
// sur mon ordinateur : 8/8/2014 13:45:20
console.log( dt.toLocaleString() );
// Pour transmettre un moment précis, il vaut mieux travailler au
// format ISO long. J'utilise ma méthode formatISO() :
Date.prototype.formatISO = function(){
this._toLen2 = function(_nowStr){
_nowStr = _nowStr.toString();
return ('0'+_nowStr).substr(-2,2);
};
this._nowFormat = 'aaaa-mm-jjThh:ii:ss.lllSzz00';
this._nowFormat = this._nowFormat.replace(/j+/, this._toLen2(this.getDate()));
this._nowFormat = this._nowFormat.replace(/m+/, this._toLen2(this.getMonth()+1));
this._nowFormat = this._nowFormat.replace(/a+/, this.getFullYear());
this._nowFormat = this._nowFormat.replace(/h+/, this._toLen2(this.getHours()));
this._nowFormat = this._nowFormat.replace(/i+/, this._toLen2(this.getMinutes()));
this._nowFormat = this._nowFormat.replace(/s+/, this._toLen2(this.getSeconds()));
this._nowFormat = this._nowFormat.replace(/l+/, this.getMilliseconds());
this._nowFormat = this._nowFormat.replace(/S+/, (this.getTimezoneOffset() < 0) ? ("+") : ("-"));
this._nowFormat = this._nowFormat.replace(/z+/, this._toLen2(Math.abs(this.getTimezoneOffset()/60)));
return this._nowFormat;
};
// sur mon ordinateur : 2014-08-08T13:45:20.375+0200
// +2h pour le fuseau horaire puisque l'on est en heure d'été.
console.log( dt.formatISO() );
// Avec le format ISO long on peut aussi convertir facilement un moment
// précis d'un autre fuseau horaire dans le nôtre.
// Voir : "http://fr.wikipedia.org/wiki/Fuseau_horaire"
// Los Angeles, Californie, États-Unis le 4 juillet 2014 à 12 h pile :
var la = new Date( "2014-07-04T12:00:00.000-0800" );
// sur mon ordinateur : 2014-07-04T22:00:00.0+0200
console.log( la.formatISO() ); |
Partager