|
| 1 | +/** |
| 2 | + * Get HTML for selected year+month |
| 3 | + * |
| 4 | + * @param int year |
| 5 | + * @param int month [0-11] |
| 6 | + * @returns string table |
| 7 | + */ |
| 8 | +function getCalendarMonthAsTable(year, month, options) { |
| 9 | + var day, i, |
| 10 | + firstDay = new Date(year, month, 1).getDay(), |
| 11 | + lastDate = new Date(year, month + 1, 0).getDate(), |
| 12 | + output = [], |
| 13 | + startDate = 1; |
| 14 | + |
| 15 | + options = $.extend({ |
| 16 | + "firstDayOfWeek": 1, // Monday |
| 17 | + "showWeekDays": true, |
| 18 | + "weekDays": ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] |
| 19 | + }, options); |
| 20 | + |
| 21 | + startDate = startDate - (firstDay - options.firstDayOfWeek); |
| 22 | + |
| 23 | + if (startDate > 1) { |
| 24 | + startDate = startDate - 7; |
| 25 | + } |
| 26 | + |
| 27 | + var cell = 0, week = 0; |
| 28 | + for (day = startDate; day <= lastDate; day++, td++) { |
| 29 | + |
| 30 | + week = Math.floor(cell++ / 7); |
| 31 | + if (!output[week]) { |
| 32 | + output[week] = []; |
| 33 | + } |
| 34 | + if (day > 0) { |
| 35 | + output[week].push('<td data-date="' + getFullDateAsNumber(year, month, day) + '">' + day + '</td>'); |
| 36 | + } else { |
| 37 | + output[week].push('<td></td>'); |
| 38 | + } |
| 39 | + } |
| 40 | + for (i = 0; i < output.length; i++) { |
| 41 | + output[i] = '<tr>' + output[i].join('') + '</tr>'; |
| 42 | + } |
| 43 | + |
| 44 | + if (options.showWeekDays) { |
| 45 | + output.head = []; |
| 46 | + for (i = 0; i < 7; i++) { |
| 47 | + output.head.push('<th>' + options.weekDays[(options.firstDayOfWeek + i) % 7] + '</th>'); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + output.body = '<tbody>' + output.join('') + '</tbody>'; |
| 52 | + output.head = output.head ? '<thead><tr>' + output.head.join('') + '</tr></thead>' : ''; |
| 53 | + |
| 54 | + return '<table>' + output.head + output.body + '</table>'; |
| 55 | + |
| 56 | + function getFullDateAsNumber(year, month, day) { |
| 57 | + var date = ('0000' + year).substr(-4) + ('00' + (month + 1)).substr(-2) + ('00' + day).substr(-2); |
| 58 | + return parseInt(date); |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +getCalendarMonthAsTable(2015, 9); |
0 commit comments