将时间戳或new Date()得到的时间转化成yyyymmddhhmmss形式

将时间戳或new Date()得到的时间转化成yyyymmddhhmmss形式

废话不多说,直接上代码:

具体逻辑是:
1.先把时间戳new Date()得到的时间转成yyyy-mm-dd hh:mm:ss 形式;
2.使用比较简单的正则即可得到。

/**
 *@descript 将时间戳或new Date()得到的时间转化成yyyymmddhhmmss形式
 */
class LocalTime {
	localTime (date, fmt = 'yyyy-MM-dd HH:mm:ss') {
	    if (!data) return ''
	    if (typeof date !== 'object' || !(date instanceof Date) {
	    	date = new Date(date)
	    }
	    let o = {
	    	'M+': date.getMonth() + 1, // 月份
	    	'd+': date.getDate(), // 日
	    	'H+': date.getHours(), // 小时
	    	'm+': date.getMinutes(), // 分
	    	's+': date.getSeconds(), // 秒
	    	'q+': Math.floor( (date.getMonth() + 3) / 3), // 季度
	    	'S': date.getMilliseconds() // 毫秒
	    }
	    if (/(y+)/.test(fmt)) {
	    	fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
	    }
	    for (let k in o) {
	    	fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k].length)))
	    }
	    return fmt.replace(/\D+/g, '')
    }
}

export default new LocalTime()

你可能感兴趣的:(将时间戳或new Date()得到的时间转化成yyyymmddhhmmss形式)