Date.prototype.Format = function (fmt) {
var o = {
"M+": this.getMonth() + 1, //月份
"d+": this.getDate(), //日
"h+": this.getHours(), //小时
"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;
}
使用方式:
new Date().Format("yyyy-MM-dd hh:mm"")
getBeforeDayDate(day) {
var date = new Date(), timestamp;
timestamp = date.getTime();
// 获取day天前的日期
return new Date(timestamp - day * 24 * 3600 * 1000);
}
getAfterDayDate(day) {
var date = new Date(), timestamp;
timestamp = date.getTime();
// 获取day天之后的日期
return new Date(timestamp + day * 24 * 3600 * 1000);
}
getCurrentMonthFirst(){
var date=new Date();
date.setDate(1);
return date;
}
/**
* 获取当前月的最后一天
*/
getCurrentMonthLast(){
var date=new Date();
var currentMonth=date.getMonth();
var nextMonth=++currentMonth;
var nextMonthFirstDay=new Date(date.getFullYear(),nextMonth,1);
var oneDay=1000*60*60*24;
return new Date(nextMonthFirstDay-oneDay);
},
5. 获取某个月份的天数
let year ="2022"
let month ="2"
var days=new Date(year, month, 0).getDate()
console.log(days)
//结果为28