Loading

JS 时间对象处理方法

时间对象各单位上的数值增减

/**
 * 时间对象的数值增减
 * @param {String} interval 增减的时间类型 y - 年 | q - 季度 | M - 月 | w - 周 | d(default) - 日 | h - 时 | m - 分 | s - 秒
 * @param {Number} number 增减的具体值
 * @param {Date} date 时间对象
 * @returns {Date}
 */
export function dateAdd(interval = 'd', number = 0, date = new Date()) {
	const methods = {
		y: 'FullYear',
		q: 'Month',
		M: 'Month',
		w: 'Date',
		d: 'Date',
		h: 'Hours',
		m: 'Minutes',
		s: 'Seconds'
	}
	const method = methods[interval]

	if (method) {
		date[`set${method}`](date[`get${method}`]() + number)
	}

	return date
}

案例

const cur = new Date();
console.log(dateAdd("y", 5, cur)); // Sun Jul 18 2027 23:20:58 GMT+0800 (中国标准时间)
console.log(dateAdd("q", 5, cur)); // Wed Oct 18 2028 23:20:58 GMT+0800 (中国标准时间)
console.log(dateAdd("M", 5, cur)); // Sun Mar 18 2029 23:20:58 GMT+0800 (中国标准时间)
console.log(dateAdd("d", 20, cur)); // Sat Apr 07 2029 23:20:58 GMT+0800 (中国标准时间)

时间格式化

/**
 * 时间格式化
 * @param {String} format 时间格式
 * @param {Date} date 时间对象
 * @returns {String}
 */
export function dateFormat(format) {
	const date = this || new Date()
	const formatStr = format || 'yyyy-MM-dd HH:mm:ss'
	const units = {
		'M+': date.getMonth() + 1,
		'd+': date.getDate(),
		'H+': date.getHours(),
		'm+': date.getMinutes(),
		's+': date.getSeconds(),
	}

	const year = date.getFullYear().toString()
	const matchArr = [
		[/yyyy/, year],
		[/yy/, year.slice(-2)],
	]

	for (const key in units) {
		if (new RegExp(`(${key})`).test(formatStr)) {
			const value = units[key].toString().padStart(2, '0')
			matchArr.push([new RegExp(key), value])
		}
	}

	for (const [reg, value] of matchArr) {
		formatStr.replace(reg, value)
	}

	return formatStr
}

案例

const cur1 = new Date("2021/5/18");
console.log(dateFormat(cur1)); // 2021-05-18 0:00:00
console.log(dateFormat(cur1, "yyyy")); // 2021
console.log(dateFormat(cur1, "yyyy-MM")); // 2021-05
console.log(dateFormat(cur1, "yyyy-MM-dd")); // 2021-05-18
console.log(dateFormat(cur1, "yyyy-MM-dd HH")); // 2021-05-18 0
console.log(dateFormat(cur1, "yyyy-MM-dd HH-mm")); // 2021-05-18 0-00
console.log(dateFormat(cur1, "yyyy-MM-dd HH-mm-ss")); // 2021-05-18 0-00-00

日期相减(获取天数)

/**
 * 日期相减(获取天数)a - b
 * @param {Date} date1 时间对象
 * @param {Date} date2 时间对象 - 默认当前时间
 * @returns {String}
 */
export function dateMinus(date1, date2 = new Date()) {
  const target = date1.getTime()
  const cur = date2.getTime()
  return Math.ceil((target - cur) / (1000 * 60 * 60 * 24))
}

案例

console.log(dateMinus(new Date('2021/5/18'), new Date('2021/5/16'))); // 2
posted @ 2021-05-18 16:17  Frank-Link  阅读(158)  评论(0编辑  收藏  举报