Many times, we can use the built-in methods of Date objects in JavaScript to format them, such as:
The code copy is as follows: var d = new Date();
console.log(d); // Output: Mon Nov 04 2013 21:50:33 GMT+0800 (China Standard Time)
console.log(d.toDateString()); // Date string, output: Mon Nov 04 2013
console.log(d.toGMTString()); // Greenwich time, output: Mon, 04 Nov 2013 14:03:05 GMT
console.log(d.toISOString()); // International Organization for Standards (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 at 10:03:05 pm
console.log(d.toLocaleTimeString()); // Convert to local time format, depending on the environment, output: 10:03:05 pm
console.log(d.toString()); // Convert to string, output: Mon Nov 04 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, 04 Nov 2013 14:03:05 GMT
If the above method cannot meet our requirements, you can also customize the function to format the time, such as:
The code copy is 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] : ("00" + date[k]).substr(("" + date[k]).length));
}
}
return format;
}
var d = new Date().format('yyyy-MM-dd');
console.log(d); // 2013-11-04