1 <!DOCTYPE html> 2 <html lang="en"> 3 4 <head> 5 <meta charset="UTF-8"> 6 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 7 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 8 <title>Document</title> 9 </head> 10 11 <body> 12 13 <script> 14 Date.prototype.Format = function (fmt) { 15 var o = { 16 "M+": this.getMonth() + 1, 17 "d+": this.getDate(), 18 "H+": this.getHours(), 19 "m+": this.getMinutes(), 20 "s+": this.getSeconds(), 21 "S+": this.getMilliseconds() 22 }; 23 //因为date.getFullYear()出来的结果是number类型的,所以为了让结果变成字符串型,下面有两种方法: 24 if (/(y+)/.test(fmt)) { 25 //第一种:利用字符串连接符“+”给date.getFullYear()+"",加一个空字符串便可以将number类型转换成字符串。 26 fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); 27 } 28 for (var k in o) { 29 if (new RegExp("(" + k + ")").test(fmt)) { 30 //第二种:使用String()类型进行强制数据类型转换String(date.getFullYear()),这种更容易理解。 31 fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(String(o[ 32 k]).length))); 33 } 34 } 35 return fmt; 36 }; 37 alert(new Date().Format('yyyy-MM-dd HH:mm:ss')) 38 alert(new Date().Format('yyyy')) 39 </script> 40 41 </body> 42 43 </html>