首页 > 代码库 > Js中的一个日期处理格式化函数

Js中的一个日期处理格式化函数

 1 //日期时间原型增加格式化方法 2  3 Date.prototype.Format = function (formatStr) { 4     var str = formatStr; 5     var Week = [‘日‘, ‘一‘, ‘二‘, ‘三‘, ‘四‘, ‘五‘, ‘六‘]; 6  7     str = str.replace(/yyyy|YYYY/, this.getFullYear()); 8     str = str.replace(/yy|YY/, (this.getYear() % 100) > 9 ? (this.getYear() % 100).toString() : ‘0‘ + (this.getYear() % 100)); 9     var month = this.getMonth() + 1;10     str = str.replace(/MM/, month > 9 ? month.toString() : ‘0‘ + month);11     str = str.replace(/M/g, month);12 13     str = str.replace(/w|W/g, Week[this.getDay()]);14 15     str = str.replace(/dd|DD/, this.getDate() > 9 ? this.getDate().toString() : ‘0‘ + this.getDate());16     str = str.replace(/d|D/g, this.getDate());17 18     str = str.replace(/hh|HH/, this.getHours() > 9 ? this.getHours().toString() : ‘0‘ + this.getHours());19     str = str.replace(/h|H/g, this.getHours());20     str = str.replace(/mm/, this.getMinutes() > 9 ? this.getMinutes().toString() : ‘0‘ + this.getMinutes());21     str = str.replace(/m/g, this.getMinutes());22 23     str = str.replace(/ss|SS/, this.getSeconds() > 9 ? this.getSeconds().toString() : ‘0‘ + this.getSeconds());24     str = str.replace(/s|S/g, this.getSeconds());25     return str;26 }

调用的时候比较简单,

1 var d=new Date();2 var str=d.Format("yyyy-MM-dd  hh:mm:ss");3 console.log(str);

Js中的一个日期处理格式化函数