Find all the days in a month with Date object?

冷暖自知 提交于 2019-11-27 03:52:03
Juan Mendes

To get a list of all days in a month, you can start with a Date on the first day of a month, increase the day until the month changes.

/**
 * @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;
}

I'm not sure from your description if the standard disable dates datepicker will work with you, so I'll answer you question directly.

You can construct an array of days for a month fairly easily by doing this:

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]); 

​ Using that array of days you can pretty much do whatever you want with it and know the day of the week as well.

Here's a loopp that runs through each month to determine the last day of that month. Javascript Date object indexes months starting at zero and if you set the day to zero it reverts back to last day of prior month. Handy for determining leap year last day for February

Date( 2012, 12, 0) will return Dec 31, 2012

Date (2012,0,0) will return Dec 31,2011

and the all important one to figure out is February with

Date ( 2012,3,0) Returns Feb 29 since leap year this year

var mos=['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec']

for (i = 0; i < 12; i++) {
    var lastDate = new Date(2012, i+1, 0);
    $('body').append('Last day of ' + mos[i] + ' is ' + lastDate.getDate()+'<br>')
}

DEMO: http://jsfiddle.net/5k8sn/1/

I have implemented the functionality you requested using a jQuery datepicker.

First, add all the dates selected in the back office to be disabled into an array

// format yyyy-mm-dd
var disabledDates = [
    "2012-10-01",
    "2012-10-02",
    "2012-10-30",
    "2012-09-12"
];

Second, specify the datepicker with two functions

$("#datepicker").datepicker({

    // only enable date if dateEnabled returns [true]
    beforeShowDay: dateEnabled,

    // once a date has been selected call dateSelected
    onSelect: dateSelected
});

Here is the definition of the required functions

function dateEnabled( d ) {

    // if date found in array disable date
    if( disabledDates.indexOf( getDate( d ) ) > -1 ) {

        return [false];

    } else {

        return [true] ;

    }
}  

Convert date to string for comparison with dates in array

function getDate( d ) {
    var day,
        month,
        year;

    day = d.getDate( );
    month = d.getMonth( ) + 1; // add 1 as getMonth returns 0 - 11
    year = d.getFullYear( );

    if( month < 10 ) month = "0" + month;
    if( day < 10 ) day = "0" + day;
    return year + "-" + month + "-" + day;
}

Once a date has been selected process it

function dateSelected( d ) { 
   // do stuff with string representation of date                                          
}

Here is a fiddle http://jsfiddle.net/KYzaR/7/

Just thought it would be worth mentioning that Array.indexOf is a recent addition to ECMA-262 standard and so in the case of IE7 and IE8 it is not supported. The following MDN page provides code that implements Array.indexOf for these browsers https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf

Cheeso

To disable dates in a datepicker, you can use the answer described here:
https://stackoverflow.com/a/12061715/48082

To choose multiple dates (as in the back-office app), you can use this plugin:
http://multidatespickr.sourceforge.net/

One liner to get all days as Date object in a month

const getDaysInMonth = (month, year) => (new Array(31)).fill('').map((v,i)=>new Date(year,month-1,i+1)).filter(v=>v.getMonth()===month-1)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!