有一个需求就是说在星期一到星期日选一天,如选择五,输出本周中星期五的格式化时间。
输入星期?,如:?等于五
输出本周中星期?的格式化时间,如:2023-02-24 17:30:01
一、方法实现
/**
* 获取本周中任意一天的时间
*/
function getTargetTimeInCurrentWeek(targetNum) {
console.log('targetNum =>', targetNum)
// 本周任意一天,例如:本周二,则得到2,本周六,则得到6,本周日,则得到7
let tarDayInWeek
if (targetNum === '一') {
tarDayInWeek = 1
} else if (targetNum === '二') {
tarDayInWeek = 2
} else if (targetNum === '三') {
tarDayInWeek = 3
} else if (targetNum === '四') {
tarDayInWeek = 4
} else if (targetNum === '五') {
tarDayInWeek = 5
} else if (targetNum === '六') {
tarDayInWeek = 6
} else if (targetNum === '日') {
tarDayInWeek = 7
} else {
console.info('getTargetTimeInCurrentWeek =>', '参数错误')
return
}
// 实例化当前时间
const currentDate = new Date()
// 今天是星期几?例如:今天是星期一,则得到1。(注:一 => 1, 二 => 2, 三 => 3, 四 => 4, 五 => 5, 六 => 6, 日 => 0)
const curDayInWeek = currentDate.getDay()
// 计算偏移量
const offset = tarDayInWeek - curDayInWeek
// 计算目标时间戳
const timestamp = currentDate.getTime() + offset * 24 * 3600 * 1000
// 转成时间对象
const targetDate = new Date(timestamp)
const year = targetDate.getFullYear() // 年份
let month = targetDate.getMonth() + 1 // 月份
month = month < 10 ? '0' + month : month.toString() // 若月份小于10则补个0
let day = targetDate.getDate(); // 日期
day = day < 10 ? '0' + day : day.toString() // 若日期小于10则补个0
const hours = targetDate.getHours()
const minutes = targetDate.getMinutes()
const seconds = targetDate.getSeconds()
return year + `-` + month + `-` + day + ` ` + hours + `:` + minutes + `:` + seconds
}
二、调用方式
getTargetTimeInCurrentWeek('五')
三、效果如下~