js时间转换

137 阅读1分钟

时间戳转换日期:

// 时间转换
formatTime(date, type) {
	// 判断传入值date是否存在
	if (!date) {
		return
	}
	// 将date时间戳转换为标准时间
	if (typeof date == 'string') {
		date = date.replace(/-/g, '/');
		if (date.indexOf('T') > -1) {
			date = date.replace(/T/g, ' ');
			var index = date.indexOf('.');
			date = date.substr(0, index);
		}
	}
	var time = new Date(date)
	// 提取年月日
	var Y = time.getFullYear()
	var M = time.getMonth() + 1
	var D = time.getDate()
	// 提取星期
	var W = time.getDay()
	// 提取时分秒
	var h = time.getHours()
	var m = time.getMinutes()
	var s = time.getSeconds()
	// 不足10的填充0
	M = M >= 10 ? M : '0' + M
	D = D >= 10 ? D : '0' + D
	h = h >= 10 ? h : '0' + h
	m = m >= 10 ? m : '0' + m
	s = s >= 10 ? s : '0' + s
	// 输出时间格式
	if (type === 1) {
		var weekDay = ['一', '二', '三', '四', '五', '六', '天']
		return Y + '-' + M + '-' + D + ' 星期' + weekDay[W] + ' ' + h + ' : ' + m + ' : ' + s // YYYY/MM/DD  W  hh:mm:ss
	} else if (type === 2) {
		return Y + '-' + M + '-' + D + ' ' + h + ':' + m + ':' + s // YYYY/MM/DD  hh:mm:ss
	} else if (type === 3) {
		return Y + '-' + M // YYYY/MM
	} else if (type === 4) {
		return Y + '-' + M + '-' + D + ' ' + h + ':' + m // YYYY/MM/DD  hh:mm
	} else {
		return Y + '-' + M + '-' + D // YYYY/MM/DD
	}
},

日期转换时间戳:

// 日期转换时间戳
turnTimeNumber(val) {
	if (val) {
		return new Date(val).getTime()
	}
},