javascript实现选择指定月份,生成选择月份的所有日期包含星期
javascript实现选择指定月份,生成选择月份的所有日期包含星期
浏览次数:2054 次
下载次数:1 次
下载积分:1 积分
评分:
实例代码:
// 将时间戳转换为日期对象
const selectedMonth = new Date(timestamp);
// 将日期设置为该月份的第一天
selectedMonth.setDate(1);
// 获取该月份的最后一天
const lastDay = new Date(selectedMonth.getFullYear(), selectedMonth.getMonth() + 1, 0);
// 星期几数组
const weekDays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
// 生成日期数组
const dates = [];
for (let date = selectedMonth; date <= lastDay; date.setDate(date.getDate() + 1)) {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const dateStr = `${year}-${month}-${day}`;
const dayOfWeek = weekDays[date.getDay()];
dates.push({ text: `${dateStr} (${dayOfWeek})`, value: dateStr });
}
// 返回日期数组
return dates;
返回结果:
[{
"text": "2023-04-01 (周六)",
"value": "2023-04-01"
}, {
"text": "2023-04-02 (周日)",
"value": "2023-04-02"
}, {
"text": "2023-04-03 (周一)",
"value": "2023-04-03"
}, {
"text": "2023-04-04 (周二)",
"value": "2023-04-04"
}, {
"text": "2023-04-05 (周三)",
"value": "2023-04-05"
}, {
"text": "2023-04-06 (周四)",
"value": "2023-04-06"
}, {
"text": "2023-04-07 (周五)",
"value": "2023-04-07"
}, {
"text": "2023-04-08 (周六)",
"value": "2023-04-08"
}, {
"text": "2023-04-09 (周日)",
"value": "2023-04-09"
}, {
"text": "2023-04-10 (周一)",
"value": "2023-04-10"
}, {
"text": "2023-04-11 (周二)",
"value": "2023-04-11"
}, {
"text": "2023-04-12 (周三)",
"value": "2023-04-12"
}, {
"text": "2023-04-13 (周四)",
"value": "2023-04-13"
}, {
"text": "2023-04-14 (周五)",
"value": "2023-04-14"
}, {
"text": "2023-04-15 (周六)",
"value": "2023-04-15"
}, {
"text": "2023-04-16 (周日)",
"value": "2023-04-16"
}, {
"text": "2023-04-17 (周一)",
"value": "2023-04-17"
}, {
"text": "2023-04-18 (周二)",
"value": "2023-04-18"
}, {
"text": "2023-04-19 (周三)",
"value": "2023-04-19"
}, {
"text": "2023-04-20 (周四)",
"value": "2023-04-20"
}, {
"text": "2023-04-21 (周五)",
"value": "2023-04-21"
}, {
"text": "2023-04-22 (周六)",
"value": "2023-04-22"
}, {
"text": "2023-04-23 (周日)",
"value": "2023-04-23"
}, {
"text": "2023-04-24 (周一)",
"value": "2023-04-24"
}, {
"text": "2023-04-25 (周二)",
"value": "2023-04-25"
}, {
"text": "2023-04-26 (周三)",
"value": "2023-04-26"
}, {
"text": "2023-04-27 (周四)",
"value": "2023-04-27"
}, {
"text": "2023-04-28 (周五)",
"value": "2023-04-28"
}, {
"text": "2023-04-29 (周六)",
"value": "2023-04-29"
}]
在上面的代码中,我们首先将时间戳转换为日期对象,并将日期设置为该月份的第一天。然后,我们获取该月份的最后一天。我们定义了一个星期几数组 weekDays,用来存储星期几的名称,这个数组的索引与日期对象中的 getDay() 方法返回值对应。使用一个 for 循环来生成每个日期,将日期格式化为"yyyy-mm-dd"的字符串,并使用 getDay() 方法获取星期几的名称,然后将日期字符串和星期几的名称添加到一个对象中,该对象有两个键值对,一个是"text",一个是"value",它们的值分别为日期字符串和日期字符串。最后,我们将该对象添加到日期数组中。最终返回日期数组。
本站素材来自用户分享,仅限学习交流请勿用于商业用途。如损害你的权益请联系客服QQ:201240120 给予处理。
还没有评论哦!