关于时间的封装

283 阅读1分钟
把时间转为日期格式或实时显示时间
function formatDate(oldDate, fmt) {
    let date
    // 可以接收String、number、Date类型(object),前两种当时间戳来处理
    if (typeof oldDate === 'string' || typeof oldDate === 'number') {
        date = new Date(+oldDate)
    } else {
        date = new Date()
    }

	// 匹配格式化的时间是否有年份
    if (/(y+)/.test(fmt)) {
    	// RegExp.$1得到匹配有多少个y
        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 (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
            let str = o[k] + ''
            // 判断要显示多少位
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? '0' + str : str)
        }
    }
    return fmt  //document.querySelector('.content').innerText = fmt 实时显示时间
}
1.将当前时间戳转为日期时间格式
formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss')
//"2019-11-25 23:46:32"
2.将毫秒数转为日期时间格式
formatDate(1574696907989, 'yyyy-MM-dd hh:mm:ss')
formatDate('1574696907989', 'yyyy-MM-dd hh:mm:ss')
//"2019-11-25 23:48:27"
3.实时显示时间
setInterval(formatDate, 1000, new Date(), 'yyyy-MM-dd hh:mm:ss')
获取一个月的天数
function getMonthDay(date) {
	const year = date ? date.split('-')[0] : new Date().getFullYear()
	const month = date ? date.split('-')[1] : new Date().getMonth() + 1
	// new Date()第3个参数默认为1,就是每个月的1号,把它设置为0时, new Date()会返回上一个月的最后一天,然后通过getDate()方法得到天数
	const now = new Date(year, month, 0)
	return now.getDate()
}
getMonthDay(2020-1-7)  //31
getMonthDay()          //31