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'))