date
时间格式化
yyyy-MM-dd hh:mm:ss
yyyy/MM/dd hh:mm:ss
yyyy/MM/dd
yyyy
Date.prototype.format = function(format) {
const o = {
'M+': this.getMonth() + 1,
'd+': this.getDate(),
'h+': this.getHours(),
'H+': this.getHours(),
'm+': this.getMinutes(),
's+': this.getSeconds(),
'q+': Math.floor((this.getMonth() + 3) / 3),
S: this.getMilliseconds()
}
if (/(y+)/.test(format)) {
format = format.replace(RegExp.$1, `${this.getFullYear()}`.substr(4 - RegExp.$1.length))
}
Object.keys(o).forEach(k => {
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
}
获取最近几个月
['2022-06', '2022-07', '2022-08', '2022-09', '2022-10', '2022-11', '2022-12']
['2022/09/10 16:35:19', '2022/10/10 16:35:19', '2022/11/10 16:35:19', '2022/12/10 16:35:19']
/** 获取最近几个月 **/
Date.prototype.getRecentMonth = function(n = 0, datetype = 'yyyy-MM') {
const monthList = []
while (n > 0) {
const date = new Date()
/** 月份少1 先增加1 **/
date.setMonth(date.getMonth() - n + 1, 1) // 这里一定设置为1 不然日期为31时,生产的数据是错乱的
monthList.push(date.format(`${datetype}`))
n--
}
return monthList
}