const getTimeFormat = (date = new Date()) => {
const getYMD = (date) => {
const sliceStr = (str) => ('0' + str).slice(-2)
const time = date.getTime() //毫秒 date的时间戳
const year = date.getFullYear() //年
const month = sliceStr(date.getMonth() + 1) //月
const day = sliceStr(date.getDate()) //日
const weekDay = date.getDay() || 7 //星期几
const ymd = `${year}-${month}-${day}`
return {
date,
time,
year,
month,
day,
weekDay,
ymd
}
}
const { date: today, time: todayTime, weekDay: todayWeek, ymd: todayYMD } = getYMD() //今天
const { time, year, month, day, weekDay, ymd } = getYMD(date) //传入的date数据
const dateStart = new Date(`${ymd} 00:00:00`).getTime() //date当天的开始时间
const dateEnd = new Date(`${ymd} 23:59:59`).getTime() //date当天的结束时间
const isToday = todayYMD === ymd
const oneDayTime = 24 * 60 * 60 * 1000
const MondayTime = dateStart - (weekDay - 1) * oneDayTime //date的周一 yyyy:mm:dd 00:00:00
const SundayTime = dateEnd + (7 - weekDay) * oneDayTime //date的周日 yyyy:mm:dd 23:59:59
// const nextMonday = dateStart + oneDayTime * (8 - todayWeek) //date的下周一 yyyy:mm:dd 00:00:00
const isThisWeek = MondayTime <= todayTime && todayTime <= SundayTime// 是否是本周
return {
today,
todayTime,
todayYMD,
todayWeek,
time,
year,
month,
day,
weekDay,
ymd,
dateStart,
dateEnd,
MondayTime,
SundayTime,
isToday,
isThisWeek
}
}
// console.log(getTimeFormat(new Date()));
// console.log(getTimeFormat(new Date(1678031999000)));
console.log(getTimeFormat(new Date(1679533199000)));
js格式化日期/年月日/是否是今天/是否是本周
于 2023-03-03 16:53:12 首次发布