JavaScript implements date formatting through regularization

    In javascript development, we will encounter the problem of date and time formatting. Generally speaking, by default, we adopt the format of yyyy-MM-dd hh: mm: ss. The simple way is to get the various fields of time, year , Month, day, hour, minute, and second, and then form such a date and time format by string concatenation. When the month, date, hour, minute, and seconds are less than 10, add 0 in front to achieve this purpose. But generally speaking, this formatting method is more rigid. When we change a formatting method, we need to rewrite a function.

     Here is an example of using regularization to implement date formatting. Its idea is very clever. It uses a map to store the month, day, hour, minute, and second, and then replaces the formatting expression by character replacement It is an expression of year, month, day, hour, minute, and second, and finally needs to count the replacement of the previous year.

    The test code is as follows. This method only needs to modify the formatting expression to achieve the date formatting purpose.

var Utils = {
	formatDate:function(time,format){
		var date = new Date(time);
		var map ={
			'M' : date.getMonth()+1,//month
			'd' : date.getDate(),//date
			'h' : date.getHours(),//hours
			'm' : date.getMinutes(),//minutes
			's' : date.getSeconds() //seconds
		};
		format = format.replace(/([yMdhms])+/g,function(all,t){
			var v = map[t];
			if(v!=undefined){
				 if(all.length>1){
					v = '0'+v;
					v = v.substr(v.length-2);
				 }
				 return v;
			}else if(t=='y'){
				return (date.getFullYear()+'').substr(4-all.length);
			}
			return all;
		});
	   return format;		   
	}
};
console.log(Utils.formatDate(new Date().getTime(),'yyyy年MM月dd日hh:mm:ss'))
console.log(Utils.formatDate(new Date().getTime(),'yyyy-MM-dd/hh:mm:ss'))
console.log(Utils.formatDate(new Date().getTime(),'yyyy-MM-dd hh:mm:ss'))

   The results are as follows:

    

Published 529 original articles · praised 287 · 1.47 million views

Guess you like

Origin blog.csdn.net/feinifi/article/details/103396694