Home > Web Front-end > JS Tutorial > JavaScript methods to format date and time and examples of custom formatting functions_javascript skills

JavaScript methods to format date and time and examples of custom formatting functions_javascript skills

WBOY
Release: 2016-05-16 16:53:10
Original
1186 people have browsed it

Many times, we can use the built-in methods of the Date object in JavaScript to format, such as:

Copy code The code 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 Standards 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: 2013 November 4
console.log(d.toLocaleString()); // Convert to local date and time format, depending on the environment, output: November 4, 2013 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 a function to format the time, such as:
Copy code The code is as follows ; .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)); ) {
                                                                                    ? date[k] : ("00" date[k]).substr(("" date[k]).length));
                                                                                                                                                    ; >var d = new Date().format('yyyy-MM-dd');
console.log(d); // 2013-11-04




Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template