Pau*_*aul 15 javascript jquery date monthcalendar datepicker
有没有办法让一个月或一年的所有日子?我正在寻找这个以禁用日期选择器中的某些特定日期,我会在后台有一个页面来选择这些天来禁用.
因此,我需要在一个月内显示所有日期,并在每天下方添加"激活或取消激活"按钮.有没有办法用Date对象找到这些日子?我发现这个链接例如:显示一个月的所有日子,但我真的不明白它,加上它是Java,我试图在javascript中找到一个解决方案.
谢谢您的帮助
Jua*_*des 57
要获取一个月中所有日期的列表,您可以从一个月Date
的第一天开始,增加直到月份更改的日期.
/**
* @param {int} The month number, 0 based
* @param {int} The year, not zero based, required to account for leap years
* @return {Date[]} List with date objects for each day of the month
*/
function getDaysInMonth(month, year) {
var date = new Date(Date.UTC(year, month, 1));
var days = [];
while (date.getMonth() === month) {
days.push(new Date(date));
date.setDate(date.getDate() + 1);
}
return days;
}
Run Code Online (Sandbox Code Playgroud)
Kyl*_*Mit 14
您可以获取指定月份的天数,然后创建一个具有该长度的新数组,并将每一天作为项目。
const getAllDaysInMonth = (month, year) =>
Array.from(
{ length: new Date(year, month, 0).getDate() },
(_, i) => new Date(year, month - 1, i + 1)
);
Run Code Online (Sandbox Code Playgroud)
const getAllDaysInMonth = (month, year) =>
Array.from(
{length: new Date(year, month, 0).getDate()}, // get next month, zeroth's (previous) day
(_, i) => new Date(year, month - 1, i + 1) // get current month (0 based index)
);
const allDatesInOctober = getAllDaysInMonth(10, 2021)
console.log(allDatesInOctober.map(x => x.toLocaleDateString([], { month: "short", day: "numeric" })))
// ['Oct 1', 'Oct 2', 'Oct 3', 'Oct 4', 'Oct 5', 'Oct 6', 'Oct 7', 'Oct 8', 'Oct 9', 'Oct 10', 'Oct 11', 'Oct 12', 'Oct 13', 'Oct 14', 'Oct 15', 'Oct 16', 'Oct 17', 'Oct 18', 'Oct 19', 'Oct 20', 'Oct 21', 'Oct 22', 'Oct 23', 'Oct 24', 'Oct 25', 'Oct 26', 'Oct 27', 'Oct 28', 'Oct 29', 'Oct 30', 'Oct 31']
Run Code Online (Sandbox Code Playgroud)
一个班轮在一个月内将所有天数作为日期对象
const getDaysInMonth = (month, year) => (new Array(31)).fill('').map((v,i)=>new Date(year,month-1,i+1)).filter(v=>v.getMonth()===month-1)
Run Code Online (Sandbox Code Playgroud)
小智 5
我不能从你的描述中确定标准的禁用日期datepicker是否适合你,所以我会直接回答你的问题.
通过这样做,您可以相当容易地构建一个月的数组:
var numOfDays = new Date(2012, 10, 0).getDate(); //use 0 here and the actual month
var days = new Array();
//This will construct an array with all the elements represent the day of the week
//(i.e. Oct 30th would be days[30-1] or days[29]) and the value would be the actual
//day of the week (i.e. Tuesday which is representing by the number 2)
for(var i=0;i<=numOfDays;i++)
{
days[i] = new Date(2012,9,i+1).getDay(); //use month-1 here
}
//This will give you a number from 0 - 6 which represents (Sunday - Saturday)
alert(days[29]);
Run Code Online (Sandbox Code Playgroud)
使用这一天你几乎可以随心所欲地做任何事情并知道一周中的某一天.