JavaScript: get an array of day names of a specified date (month / year)

How can I get the names of a given month / year all month long? eg:

var year = "2000";
var month = "7"

... some code here that makes an array with names of days of the given month...

and the output looks something like this:

Array ("1. Sunday", "2. Monday", "3. Tuesday", ... "29. Thursday", "30. Friday", "31. Saturday");

Regards, Chris

+5
source share
5 answers

This should do what you requested.

function getDaysArray(year, month) {
    var numDaysInMonth, daysInWeek, daysIndex, index, i, l, daysArray;

    numDaysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    daysInWeek = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
    daysIndex = { 'Sun': 0, 'Mon': 1, 'Tue': 2, 'Wed': 3, 'Thu': 4, 'Fri': 5, 'Sat': 6 };
    index = daysIndex[(new Date(year, month - 1, 1)).toString().split(' ')[0]];
    daysArray = [];

    for (i = 0, l = numDaysInMonth[month - 1]; i < l; i++) {
        daysArray.push((i + 1) + '. ' + daysInWeek[index++]);
        if (index == 7) index = 0;
    }

    return daysArray;
}
+9
source

try it

<!DOCTYPE html>
<html>
<body>

<p id="demo">Click the button to display todays day of the week.</p>

<button onclick="myFunction()">Try it</button>

<script type="text/javascript">
function daysInMonth(month,year) {
    return new Date(year, month, 0).getDate();
}

function myFunction()
{var b=[],weekday = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],month=7,year=2000;
for(var i=1,l=daysInMonth(month,year);i<l;i++){
var d = new Date(year,month-1,i);
b.push(i+"."+weekday[d.getDay()]);
}
console.log(b);}//b is the desired array
</script>

</body>
</html>
+2
source

, JavaScript Date. . , . (jsFiddle)

var daysOfTheWeek = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

function getDisplay(month, day, year) {
    var d = new Date(year, month-1, day);
    return day + '. ' + daysOfTheWeek[d.getDay()];
}

array_push($dates, getDisplay(7, 4, 2012));
0

.

<script>
var weekday = ['Sunday', 'Monday', 'Tuesday', 'Wednesday',
               'Thursday', 'Friday', 'Saturday'];
var month = '7';
var year = '2012';
realMonth = parseInt(month,10)-1;
var monthObj = {};
for(var i=1;i<30;i++)
{
    var d = new Date(year,realMonth,i);              
    monthObj[i] = weekday[d.getDay()];
}
console.log(monthObj);
</script>
0

All Articles