Preface
Javascript date formatting is quite common in daily development. So below I will share with you two examples of using Javascript time format format function. Let’s take a look.
Method 1
Date.prototype.pattern=function(fmt) { var o = { "M+" : this.getMonth()+1, //month "d+" : this.getDate(), //date "h+" : this.getHours()%12 == 0 ? 12 : this.getHours()%12, //hour "H+" : this.getHours(), //hour "m+" : this.getMinutes(), //min "s+" : this.getSeconds(), //second "q+" : Math.floor((this.getMonth()+3)/3), //quarter "S" : this.getMilliseconds() //ms}; var week = { "0" : "/u65e5", "1" : "/u4e00", "2" : "/u4e8c", "3" : "/u4e09", "4" : "/u56db", "5" : "/u4e94", "6" : "/u516d" }; if(/(y+)/.test(fmt)){ fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); } if(/(E+)/.test(fmt)){ fmt=fmt.replace(RegExp.$1, ((RegExp.$1.length>1) ? (RegExp.$1.length>2 ? "/u661f/u671f" : "/u5468") : "")+week[this.getDay()+""]); } for(var k in o){ if(new RegExp("("+ k +")").test(fmt)){ fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length))); } } return fmt; }Calling methods
var date = new Date(); window.alert(date.pattern("yyyy-MM-dd hh:mm:ss"));Method 2:
// Expansion of Date, convert Date into String in the specified format// Month (M), Day (d), Hours (h), Minutes (m), Seconds (s), and Quarters (q) can be used for 1-2 placeholders, // Year (y) can be used for 1-4 placeholders, and milliseconds (S) can be used for 1 placeholder (a number of 1-3 digits) // Example: // (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 // (new Date()).Format("yyyy-Md h:m:sS") ==> 2006-7-2 8:9:4.18 Date.prototype.Format = function (fmt) { var o = { "M+": this.getMonth() + 1, //month "d+": this.getDate(), //day "h+": this.getHours(), //hours "m+": this.getMinutes(), //min "s+": this.getSeconds(), //seconds "q+": Math.floor((this.getMonth() + 3) / 3), //Quarterly "S": this.getMilliseconds() //milliseconds}; if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); for (var k in o) if (new RegExp("("+k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); return fmt;}Calling method:
var harooms1 = new Date().Format("yyyy-MM-dd"); var harooms2= new Date().Format("yyyy-MM-dd hh:mm:ss"); alert(harooms1); alert(harooms2);Summarize
The above is all about this article. The above two methods are from the Internet and are both available after verification and testing. They are also more convenient. When you use them, you can encapsulate them. Just call them directly in your function. These two time formatting functions are still relatively good! I hope it will help you in your study or work. If you have any questions, please leave a message to communicate.