Share a date Formatting Function implemented by JavaScript, javascript function
Because you often need to format the date at work, unlike the back-end, there are convenient methods to call, you can define a format method in the date object prototype, as shown below:
Copy codeThe Code is as follows:
// Added the formatting method for the date and time prototype.
Date. prototype. Format = function (formatStr ){
Var str = formatStr;
Var Week = ['day', 'yi', '2', '3', '4', '5', '6'];
Str = str. replace (/yyyy | YYYY/, this. getFullYear ());
Str = str. replace (/yy | YY/, (this. getYear () % 100)> 9? (This. getYear () % 100). toString (): '0' + (this. getYear () % 100 ));
Var month = this. getMonth () + 1;
Str = str. replace (/MM/, month> 9? Month. toString (): '0' + month );
Str = str. replace (/M/g, month );
Str = str. replace (/w | W/g, Week [this. getDay ()]);
Str = str. replace (/dd | DD/, this. getDate ()> 9? This. getDate (). toString (): '0' + this. getDate ());
Str = str. replace (/d | D/g, this. getDate ());
Str = str. replace (/hh | HH/, this. getHours ()> 9? This. getHours (). toString (): '0' + this. getHours ());
Str = str. replace (/h | H/g, this. getHours ());
Str = str. replace (/mm/, this. getMinutes ()> 9? This. getMinutes (). toString (): '0' + this. getMinutes ());
Str = str. replace (/m/g, this. getMinutes ());
Str = str. replace (/ss | SS/, this. getSeconds ()> 9? This. getSeconds (). toString (): '0' + this. getSeconds ());
Str = str. replace (/s | S/g, this. getSeconds ());
Return str;
}
It is relatively simple to call, for example:
Copy codeThe Code is as follows:
Var d = new Date ();
Var str = d. Format ("yyyy-MM-dd hh: mm: ss ");
Console. log (str );