如何在 JavaScript 中查找星期几
Posted
技术标签:
【中文标题】如何在 JavaScript 中查找星期几【英文标题】:How to find the days of the week in JavaScript 【发布时间】:2021-11-19 15:30:27 【问题描述】:我正在尝试查找从今天到周日的工作日。由于今天是星期一,我想显示从星期一到星期日的日期,但是明天,我希望我的程序从星期二到星期日工作。
dateSets()
let firstDayOfWeek = "";
let dates = [];
firstDayOfWeek = new Date();
let sunday = new Date();
sunday.setDate(sunday.getDate() - sunday.getDay() + 7);
const diff = sunday.getDate() - firstDayOfWeek.getDate();
dates.push(new Date());
for (let i = 0; i < diff; i++)
dates.push(
new Date(firstDayOfWeek.setDate(firstDayOfWeek.getDate() + 1))
);
return dates;
,
还有一个查找星期几的函数:
getDateOfWeek(week, year)
let simple = new Date(year, 0, 1 + (week - 1) * 7);
let dow = simple.getDay();
let weekStart = simple;
if (dow <= 4) weekStart.setDate(simple.getDate() - simple.getDay() + 1);
else weekStart.setDate(simple.getDate() + 8 - simple.getDay());
return weekStart;
,
但它不起作用,在数据集中,只显示星期一,但不显示其他日期,我不明白原因。如果你能帮我解决这个问题,我会非常高兴。 谢谢...
【问题讨论】:
What is a debugger and how can it help me diagnose problems? 和 How to debug small programs 您想要像Monday, Tuesdays ...
这样的工作日或像 27/09/2021
这样的日期?
@navnath 喜欢这个 27/09/2021 但我的问题是本周的,它只显示星期一,我认为这是因为他的月份在这周发生了变化。
@RobG 是的,我猜到了,但做不到你能告诉我怎么做吗?
【参考方案1】:
function getWeekDates()
const dates = [new Date()]; // today
const curr = new Date();
const remDaysCount = 7-curr.getDay();
for(let i=1; i<= remDaysCount; i++)
// increase current Date by 1 and set to current Date
const nextDate = curr.setDate(curr.getDate()+1);
dates.push(new Date(nextDate));
return dates;
console.log(getWeekDates());
【讨论】:
【参考方案2】:这是您的选择,但如果您安装 NodeJS 并在 cmd 中打开文件夹并输入“npm init”和“npm I days”并打开编辑器并输入
var days = require('days');
console.log(days); // ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
控制台将显示一周中的所有日期,如果您想要特定日期,可以执行以下操作
var days = require('days');
console.log(days[0]); //Sunday
如果您在安装 NodeJS 方面需要帮助,请观看 YouTube 视频或回复此评论,我会提供帮助
【讨论】:
【参考方案3】:let firstDayOfWeek = "";
let dates = [];
firstDayOfWeek = new Date();
let sunday = new Date();
sunday.setDate(sunday.getDate() - sunday.getDay() + 7);
//const diff = sunday.getDate() - firstDayOfWeek.getDate();
//Try this code
var timeDiff = Math.abs(sunday.getTime() - firstDayOfWeek.getTime());
var diff = Math.ceil(timeDiff / (1000 * 3600 * 24));
dates.push(new Date());
for (let i = 0; i < diff; i++)
dates.push(
new Date(firstDayOfWeek.setDate(firstDayOfWeek.getDate() + 1))
);
return dates;
【讨论】:
【参考方案4】:您的问题在这里:
const diff = sunday.getDate() - firstDayOfWeek.getDate()
当前日期为 9 月 27 日,下周日为 10 月 3 日,因此 diff 为 -4,for 循环测试 i < diff
从一开始就是错误的。考虑使用循环并将日期从今天开始递增到星期天。
function getDaysToSunday(date = new Date())
let d = new Date(+date);
let result = [];
do
result.push(new Date(+d));
d.setDate(d.getDate() + 1);
while (d.getDay() != 1)
return result;
console.log(getDaysToSunday().map(d=>d.toDateString()));
【讨论】:
以上是关于如何在 JavaScript 中查找星期几的主要内容,如果未能解决你的问题,请参考以下文章