如何解决获取接下来 3 个月的星期四并将日期输出到选择中
我需要获取接下来 3 个月星期四的日期,然后将这些日期输出到选择输入中,值的格式为 dd/mm/yyyy,但选择显示为“2021 年 4 月 12 日星期四”,理想情况下在 jQuery 中,但 PHP 也可以。
<select>
<option value="08/04/2021">Thursday 8th April 2021</option>
<option value="15/04/2021">Thursday 15th April 2021</option>
<option value="22/04/2021">Thursday 22nd April 2021</option>
etc
etc
</select>
我发现这个 jsfiddle 可以获得当月的所有星期四,但我需要它是从今天开始的接下来 3 个月的星期四。 (如果今天是星期四,也包括今天)。
如果是从今天起的接下来的 12 个星期四就可以了。
解决方法
要获得接下来的 X 个月,您可以:
function getNextMonths(num,include_current = false) {
let current = new Date();
let months = [];
if (include_current) {
months.push(current);
num--;
}
for (let i = 1; i <= num; i++) {
let next = new Date();
next.setDate(1);
next.setMonth(current.getMonth() + i);
months.push(next);
}
return months;
}
console.log(getNextMonths(3)); // Gives you the next three months
从那里,您只需要循环月份并评估它们的天数:
function getDayOfWeek(num_week_day,dates) {
let days = [];
for (let i = 0; i < dates.length; i++) {
// Evaluate current month
let current = {
year: dates[i].getFullYear(),month: dates[i].getMonth()
};
current.days = new Date(current.year,current.month + 1,0).getDate();
// Loop & evaluate days
for (let d = 1; d <= current.days; d++) {
let date = new Date(current.year,current.month,d);
if (date.getDay() == num_week_day) {
days.push(date);
}
}
}
return days;
}
// Get all Thursdays (4th day of the week) within the next 3 months.
console.log(getDayOfWeek(4,getNextMonths(3)));
// Get Thursdays within the next 3 months including the current one
console.log(getDayOfWeek(4,getNextMonths(3,true)));
// Get Thursdays within the next 3 months including the current one...
let thursdays = getDayOfWeek(4,true));
//...but keep only those Thursdays that are in the future
let today = new Date();
let filtered = thursdays.filter(function (date) {
return date.getTime() >= today.getTime();
});
console.log(thursdays,filtered);
这两个函数都返回一个由 Date
对象组成的数组 - 您可能需要根据需要对其进行格式化。有关如何执行此操作的不同方法,请参阅此线程:
正如评论中通过引用 this thread 所指出的,您可能还需要考虑将 moment.js 用于 JavaScript 日期操作。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。