Plusieurs fois, nous pouvons utiliser les méthodes intégrées des objets de date en JavaScript pour les formater, tels que:
La copie de code est la suivante: var d = new Date ();
Console.log (D);
Console.log (D.TodateString ());
Console.log (D.TogMtString ());
Console.log (D.ToSoString ());
Console.log (d.tojson ());
console.log (d.tolocaledatestring ());
console.log (d.tolocalestring ());
console.log (d.tolocaletimestring ());
Console.log (D.ToString ());
console.log (d.totimestring ());
console.log (d.toutcstring ());
Si la méthode ci-dessus ne peut pas répondre à nos exigences, vous pouvez également personnaliser la fonction pour formater l'heure, comme:
La copie de code est la suivante:
Date.prototype.format = fonction (format) {
var date = {
"M +": this.getMonth () + 1,
"d +": this.getDate (),
"h +": this.gethours (),
"M +": this.getMinutes (),
"s +": this.getSeconds (),
"q +": math.floor ((this.getMonth () + 3) / 3),
"S +": this.getMilliseconds ()
};
if (/(y+)/i.test(format)) {
format = format.replace (regexp. 1 $, (this.getlyear () + '') .substr (4 - regexp. 1.Lengle));
}
pour (var k en date) {
if (new regexp ("(" + k + ")"). test (format)) {
format = format.replace (regexp. 1 $, regexp. 1 1.Length == 1
? Date [k]: ("00" + date [k]). substr (("" + date [k]). Longueur));
}
}
format de retour;
}
var d = new Date (). Format ('yyyy-mm-dd');
console.log (d); // 2013-11-04