js时间处理

1. 获取年月日 时分秒

const getDate = (timestamp, dateSign = 1, marker = '-') => {
	//时间戳为10位需*1000,时间戳为13位的话不需乘1000
	let date = new Date(timestamp), 
		Y = date.getFullYear(),
		M = date.getMonth() + 1,
		D = date.getDate(),
		h = date.getHours(),
		m = date.getMinutes(),
		s = date.getSeconds(),
		result;

	switch (dateSign) {
		case 3:
			result = [Y, M, D].map(formatquantityber).join(marker);
			break;
		case 2:
			result = [h, m, s].map(formatquantityber).join(':');
			break;
		case 1:
		default:
			result = [Y, M, D].map(formatquantityber).join(marker) + ' ' + [h, m, s].map(formatquantityber).join(
				':')
			break;
	}

	return result;
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

2. 检查日期是否合法

const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());
    
isDateValid("December 17, 1995 03:24:00");
// Result: true

3. 检查日期位于一年中的第几天

const dayOfYear = (date) =>
      Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);
    
dayOfYear(new Date());

4. 计算两个日期相差多少天

const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000)
    
dayDif(new Date("2020-10-21"), new Date("2021-10-22"))
// Result: 366

5. 将连在一起的 年月日时分秒 字符串,转为为标准时间

var time='20190306214635'
time.replace(/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/g, '$1-$2-$3 $4:$5:$6');
// Result: 2019-03-06 21:46:35

6. 检查日期位于一年中的第几周

const weekOfYear = (date) =>
	Math.ceil((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24 / 7);

weekOfYear(new Date('2021-13-19'))	

7. 获取日期的周起始时间

const getStartDate = date => {
	let nowData = new Date(date);
	//获取今天的是周几
	let currentDay = nowData.getDay() || 7;
	let monDayTime = nowData.getTime() - (currentDay - 1) * 24 * 60 * 60 * 1000; // 获取周一的时间戳
	let sunDayTime = nowData.getTime() + (7 - currentDay) * 24 * 60 * 60 * 1000; // 获取周日的时间戳

	return [
		new Date(monDayTime).toLocaleDateString(),
		new Date(sunDayTime).toLocaleDateString()
	]
}

getStartDate(new Date('2021-13-19'))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值