/**
* @param date 时间搓
* @param fmt 需要转换的时间格式:例如: 'yyyy-MM-dd hh:mm:ss'
* @example formatDate(+new Date,'yy-MM-dd hh:mm')
*/
function formatDate(date, fmt) {
// 年份
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
}
// 月份/日/时/分/秒 正则对象表
let o = {
'M+': date.getMonth() + 1,
'd+': date.getDate(),
'h+': date.getHours(),
'm+': date.getMinutes(),
's+': date.getSeconds()
}
// 使用 for 去遍历 构造出来的 正则函数,并且对 时间搓 date进行匹配
for (let k in o) {
if (new RegExp(`(${k})`).test(fmt)) {
let str = o[k] + '' // 转换成字符串
// 如果匹配到一位数,就直接输出,或者补个0
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str))
}
}
return fmt
}
先将当前时间转化为时间戳,这里代表的是前一个月到当前的时间,利用时间戳进行相加减,
一个月的时间戳也就是 :
24 * 60 * 60 * 1000 * 30(这几个数字分别表示的是24小时 60分钟 60秒 1000毫秒 30天)
要计算其他时间的也是同理,最后这里是调用这个方法来指定'yyyy-MM-dd'格式的两个参数 beginDateTime(开始时间)和endDateTime(结束时间)
const parmas = {
beginDateTime: formatDate(new Date(new Date().getTime() - 24 * 60 * 60 * 1000 *30),'yyyy-MM-dd'),//当前时间到距当前时间一个月的时间段
endDateTime: formatDate(new Date(), 'yyyy-MM-dd')//当前时间
}