Suite à une récente discussion sur le forum : formatage de date, j'ai créé une petite fonction de formatage.
La chaine retournée est par défaut du type "jj/mm/aaaa", mais il est possible de passer une chaine à la fonction pour préciser le format souhaité.
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/*
 * 	Formatage utilisé :
 * 		j : jour du mois
 * 		m : mois
 * 		a : année
 * 		h : heure
 * 		i : minutes
 * 		s : secondes
 */
Date.prototype.format = function(){
	this._nowFormat = arguments[0] || 'jj/mm/aaaa';
	this._toLen2 = function(_nowStr){
		_nowStr = _nowStr.toString();
		return ('0'+_nowStr).substr(-2,2);
	};
	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()));
	return this._nowFormat;
};
L'utilisation est relativement simple, il suffit d'appeler la méthode format() à un objet Date :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
var now = new Date();
alert(now.format());
Page de test : http://dmouronval.developpez.com/format-date/