JS中日期格式化,加一天加一月等等
阿新 • • 發佈:2019-02-10
Date.prototype.ToString = function (format) { var o = { "M+": this.getMonth() + 1, //month "d+": this.getDate(), //day "h+": this.getHours(), //hour "m+": this.getMinutes(), //minute "s+": this.getSeconds(), //second "q+": Math.floor((this.getMonth() + 3) / 3), //quarter "S": this.getMilliseconds() //millisecond } if (/(y+)/.test(format)) format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); for (var k in o) if (new RegExp("(" + k + ")").test(format)) format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)); return format; } Date.prototype.AddMonths = function (m) { var temp = new Date(this.getFullYear(), this.getMonth(), this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds(), this.getMilliseconds()); temp.setMonth(temp.getMonth() + m); return temp; } Date.prototype.AddDays = function (d) { var temp = new Date(this.getFullYear(), this.getMonth(), this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds(), this.getMilliseconds()); temp.setDate(temp.getDate() + d); return temp; } Date.prototype.AddHours = function (h) { var temp = new Date(this.getFullYear(), this.getMonth(), this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds(), this.getMilliseconds()); temp.setHours(temp.getHours() + h); return temp; } Date.prototype.AddMinutes = function (m) { var temp = new Date(this.getFullYear(), this.getMonth(), this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds(), this.getMilliseconds()); temp.setMinutes(temp.getMinutes() + m); return temp; } String.prototype.ToDate = function () { var splitChar = '-'; if (this.indexOf('-') > 0) { splitChar = '-'; } else if (this.indexOf('/') > 0) { splitChar = '/'; } var tempStrs = this.split(" "); var dateStrs = tempStrs[0].split(splitChar); var year = parseInt(dateStrs[0], 10); var month = parseInt(dateStrs[1], 10) - 1; var day = parseInt(dateStrs[2], 10); var hour = 0; var minute = 0; var second = 0; if ($.trim(tempStrs[1]) != "") { var timeStrs = tempStrs[1].split(":"); var hour = parseInt(timeStrs[0], 10); var minute = parseInt(timeStrs[1], 10) - 1; var second = parseInt(timeStrs[2], 10); } return new Date(year, month, day, hour, minute, second); }