在JS中,通过当天的时间戳,来获取当前一周每天是周几以及对应的日期。
// 获取当前时间戳
const timestamp = new Date(this.pUseForm.start_day).getTime()
// 创建 Date 对象
const date = new Date(timestamp)
// 获取当前日期是周几
const currentDay = date.getDay()
// 计算周日的日期
const sunday = new Date(date)
sunday.setDate(date.getDate() - currentDay)
// 计算周六的日期
const saturday = new Date(date)
saturday.setDate(date.getDate() + (6 - currentDay))
// 将日期格式化为 "YYYY-mm-dd"
const formatOptions = {
year: 'numeric',
month: '2-digit',
day: '2-digit'
}
const sundayFormatted = sunday.toLocaleDateString(
undefined,
formatOptions
)
const saturdayFormatted = saturday.toLocaleDateString(
undefined,
formatOptions
)
let arr = [{day: 1,week: '日'},{day: 2,week: '一'},{day: 3,week: '二'},{day: 4,week: '三'},{day: 5,week: '四'},{day: 6,week: '五'},{day: 7,week: '六'}]
for (let i = 0; i < 7; i++) {
arr[i].day =
Number(sundayFormatted.substring(sundayFormatted.length - 2)) + i
}
在JS中,通过当天的时间戳,来获取当前月每天是周几以及对应的日期。
// 获取当前时间戳
const timestamp = new Date(this.pUseForm.start_day).getTime()]
// 创建 Date 对象
const date = new Date(timestamp)
// 获取当前月份的年份和月份
const year = date.getFullYear()
const month = date.getMonth()
// 计算第一天的日期
const firstDay = new Date(year, month, 1)
// 计算下个月的第一天
const nextMonth = month === 11 ? 0 : month + 1
const nextMonthFirstDay = new Date(year, nextMonth, 1)
// 计算最后一天
const lastDay = new Date(nextMonthFirstDay - 1)
// 格式化日期为 "YYYY-mm-dd"
const options = { year: 'numeric', month: '2-digit', day: '2-digit' }
const firstDayFormatted = firstDay.toLocaleDateString(
undefined,
options
)
const lastDayFormatted = lastDay.toLocaleDateString(undefined, options)
// 创建存储结果的数组
const monthDates = []
// 创建星期数的中文汉字映射表
const weekDayMap = ['日', '一', '二', '三', '四', '五', '六']
// 循环获取每天的日期和对应的星期数
for (let day = firstDay.getDate(); day <= lastDay.getDate(); day++) {
const currentDate = new Date(year, month, day)
const formattedDate = currentDate.getDate()
const weekDay = weekDayMap[currentDate.getDay()]
monthDates.push({ day: formattedDate, week: weekDay })
}