您的位置:首页 > Web前端 > JavaScript

JS中日期格式化,加一天加一月等等

2016-09-05 11:09 295 查看
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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息