JS_js获取当前时间 年月日 时分秒(y-m-d h:i:s),yyyy-MM-dd HH:mm:ss

方法一

Date.prototype.format = function (format) {
           var args = {
               "M+": this.getMonth() + 1,
               "d+": this.getDate(),
               "h+": this.getHours(),
               "m+": this.getMinutes(),
               "s+": this.getSeconds(),
               "q+": Math.floor((this.getMonth() + 3) / 3),  //quarter
               "S": this.getMilliseconds()
           };
           if (/(y+)/.test(format))
               format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
           for (var i in args) {
               var n = args[i];
               if (new RegExp("(" + i + ")").test(format))
                   format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? n : ("00" + n).substr(("" + n).length));
           }
           return format;
       };
//调用方法
 
alert(new Date().format("yyyy-MM-dd hh:mm:ss:S"));
alert(new Date().format("yyyy-MM-dd hh:mm:ss"));

方法二

封装方法:

function getDate(formatStr, fdate){
	 var fTime, fStr = 'ymdhis';
	 if (!formatStr)
	 	formatStr= "y-m-d h:i:s";
	 if (fdate)
	 	fTime = new Date(fdate);
	 else
	 	fTime = new Date();
	 var formatArr = [
		 fTime.getFullYear().toString(),
		 (fTime.getMonth()+1).toString(),
		 fTime.getDate().toString(),
		 fTime.getHours().toString(),
		 fTime.getMinutes().toString(),
		 fTime.getSeconds().toString() 
	 ];
	 for (var i=0; i<formatArr.length; i++){
	 	formatStr = formatStr.replace(fStr.charAt(i), formatArr[i]);
	 }
	 return formatStr;
}

方法调用:

getDate('y-m-d h:i:s',new Date());	//"2020-12-3 15:29:49"
getDate('y-m-d',new Date());		//"2020-12-3"
getDate('h:i:s',new Date());		//"15:30:39"

你可能感兴趣的:(#,JS)