js日期格式化(javascript Date format)
1 由于经常要在页面用到日期的显示,一般情况下如果数据库里面的日期类型是date,后台查询的时候如果不做处理的话,在前端页面显示的就会是Object的类型,不显示实际的数值,因此可以在js上将数据处理并在页面显示: 2 // 对Date的扩展,将 Date 转化为指定格式的String 3 // 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符, 4 // 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 5 // 例子: 6 // (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2008-07-02 08:09:04.423 7 // (new Date()).Format("yyyy-M-d h:m:s.S") ==> 2008-7-2 8:9:4.18 8 Date.prototype.Format = function (fmt) { 9 var o = { 10 "M+": this.getMonth() + 1, //月份 11 "d+": this.getDate(), //日 12 "h+": this.getHours(), //小时 13 "E" : this.getDay(), //周几 14 "m+": this.getMinutes(), //分 15 "s+": this.getSeconds(), //秒 16 "q+": Math.floor((this.getMonth() + 3) / 3), //季度 17 "S": this.getMilliseconds() //毫秒 18 }; 19 if (/(y+)/.test(fmt)) { 20 fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); 21 } 22 23 for ( var k in o) { 24 if (new RegExp("(" + k + ")").test(fmt)) { 25 fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k]: ("00" + o[k]).substr(("" + o[k]).length)); 26 } 27 } 28 return fmt; 29 } 30 调用: 31 var time1 = new Date().Format("yyyy-MM-dd"); //年月日 32 var time2 = new Date().Format("yyyy-MM-dd HH:mm:ss");//年月日 时分秒 33 或者人为的定义: 34 var date = new Date().Format("MM月dd号");//显示当前日期是几月几号 35 在比如获取当前的是日期是星期几 36 var week = ["星期日","星期一","星期二","星期三","星期四","星期五","星期六"]; 37 var z = new Date().Format("E"); 38 //这里获取的是一个数字比如周日是0,依次类推 39 console.log(week[z]);//打印出今天是星期几