<h1><h6><span style="font-weight: normal;">由于经常要在页面用到日期的显示,一般情况下如果数据库里面的日期类型是date,后台查询的时候如果不做处理的话,在前端页面显示的就会是Object的类型,不显示实际的数值,因此可以在js上将数据处理并在页面显示:</span></h6></h1>// 对Date的扩展,将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,
// 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子:
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2008-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S") ==> 2008-7-2 8:9:4.18
Date.prototype.Format = function (fmt) {
var o = {
"M+": this.getMonth() + 1, //月份
"d+": this.getDate(), //日
"h+": this.getHours(), //小时
"E" : this.getDay(), //周几
"m+": this.getMinutes(), //分
"s+": this.getSeconds(), //秒
"q+": Math.floor((this.getMonth() + 3) / 3), //季度
"S": this.getMilliseconds() //毫秒
};
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;
}
调用:
var time1 = new Date().Format("yyyy-MM-dd"); //年月日
var time2 = new Date().Format("yyyy-MM-dd HH:mm:ss");//年月日 时分秒
或者人为的定义:
var date = new Date().Format("MM月dd号");//显示当前日期是几月几号
在比如获取当前的是日期是星期几
var week = ["星期日","星期一","星期二","星期三","星期四","星期五","星期六"];
var z = new Date().Format("E");
//这里获取的是一个数字比如周日是0,依次类推
console.log(week[z]);//打印出今天是星期几
js日期格式化(javascript Date format)
最新推荐文章于 2025-01-04 10:04:56 发布
