其他分享
首页 > 其他分享> > Vue 时间格式化dateFormat

Vue 时间格式化dateFormat

作者:互联网

JavaScript中对时间格式化的工具类封装

export default {
	dateFormat(fmt, date) {
		let ret
		const opt = {
			'y+': date.getFullYear().toString(), // 年
			'M+': (date.getMonth() + 1).toString(), // 月
			'd+': date.getDate().toString(), // 日
			'H+': date.getHours().toString(), // 时
			'm+': date.getMinutes().toString(), // 分
			's+': date.getSeconds().toString(), // 秒
			// 有其他格式化字符需求可以继续添加,必须转化成字符串
		}
		for (let k in opt) {
			ret = new RegExp('(' + k + ')').exec(fmt)
			if (ret) {
				fmt = fmt.replace(
					ret[1],
					ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, '0')
				)
			}
		}
		return fmt
	},
	/// 保留n位小数
	toFixed(value, n = 2) {
		if (value) {
			return value.toFixed(n)
		}
		return (0.00.toFixed(n))
	}
}

使用:

  let effectStartTime = this.utils.dateFormat('yyyy-MM-dd HH:mm', new Date())

在vue中通过toFixed(n)可以将字符串转换成对应位数的小数 但是有时候字符串为空值时就会出现找到对应方法的情况,针对这中情况 通过可以封装一个方法 来出来异常情况

toFixed("124",2)    返回结果124.00

标签:opt,Vue,格式化,dateFormat,fmt,ret,toFixed,toString,date
来源: https://www.cnblogs.com/qqcc1388/p/16195127.html