Como geralmente é necessário formatar datas no trabalho, diferentemente do back -end, existem métodos convenientes para ligar e você pode definir um método de formato no protótipo de objeto Data, consulte o seguinte:
A cópia do código é a seguinte:
// Adicione o método de formatação para o protótipo de data e hora
Date.prototype.format = function (formatStr) {
var str = formatStr;
var semana = ['dia', 'um', 'dois', 'três', 'quatro', 'cinco', 'seis'];
str = str.place (/yyyy | aaaa/, this.getlyear ());
str = str.place (/yy | yy/, (this.getyear () % 100)> 9? (this.getyear () % 100) .toString (): '0' + (this.getyear () % 100));
var mês = this.getMonth () + 1;
str = str.place (/mm/, mês> 9? mês.toString (): '0' + mês);
str = str.place (/m/g, mês);
str = str.place (/w | w/g, semana [this.getday ()]);
str = str.place (/dd | dd/, this.getDate ()> 9? this.getDate (). tostring (): '0' + this.getDate ());
str = str.place (/d | d/g, this.getDate ());
str = str.place (/hh | hh/, this.gethours ()> 9? this.gethours (). tostring (): '0' + this.gethours ());
str = str.place (/h | h/g, this.gethours ());
str = str.place (/mm/, this.getminutes ()> 9? this.getminutes (). tostring (): '0' + this.getminutes ());
str = str.place (/m/g, this.getminutes ());
str = str.place (/ss | ss/, this.getSeconds ()> 9? this.getSeconds (). ToString (): '0' + this.getSeconds ());
str = str.place (/s | s/g, this.getSeconds ());
retornar str;
}
É relativamente simples de chamar, por exemplo:
A cópia do código é a seguinte:
var d = new Date ();
var str = d.format ("yyyy-mm-dd hh: mm: ss");
console.log (str);