Many times, we can use the built-in methods of the Date object in JavaScript to format it, such as:
Copy Code code as follows:
var d = new Date ();
Console.log (d); Output: Mon Nov 2013 21:50:33 gmt+0800 (China Standard Time)
Console.log (D.todatestring ()); Date string, output: Mon Nov 04 2013
Console.log (D.togmtstring ()); GMT, Output: Mon, Nov 2013 14:03:05 GMT
Console.log (D.toisostring ()); International Standard Organization (ISO) format, output: 2013-11-04t14:03:05.420z
Console.log (D.tojson ()); Output: 2013-11-04t14:03:05.420z
Console.log (D.tolocaledatestring ()); Convert to local date format, depending on the environment, output: November 4, 2013
Console.log (D.tolocalestring ()); Convert to local date and time format, depending on the environment, output: November 4, 2013 10:03:05
Console.log (D.tolocaletimestring ()); Convert to local time format, depending on the environment, output: 10:03:05
Console.log (D.tostring ()); Convert to String, output: Mon Nov 2013 22:03:05 gmt+0800 (China Standard Time)
Console.log (D.totimestring ()); Convert to time string, output: 22:03:05 gmt+0800 (China Standard Time)
Console.log (D.toutcstring ()); Convert to World time, output: Mon, Nov 2013 14:03:05 GMT
If the above method does not meet our requirements, you can also customize the function to format the time, such as:
Copy Code code as follows:
Date.prototype.format = function (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.getfullyear () + "). substr (4-regexp.$1.length));
}
For (var k in date) {
if (new RegExp ("+ K +")). Test (format)) {
Format = Format.replace (regexp.$1, regexp.$1.length = 1
? Date[k]: ("+ date[k]"). substr (("" "+ date[k]). length);
}
}
return format;
}
var d = new Date (). Format (' Yyyy-mm-dd ');
Console.log (d); 2013-11-04