开发者

get days of a month in JS/Prototype

I´m looking for a method, which returns all days of a given month. I couldn't find anything helpful at the standard date() functions.

i.e.:

getDays(2010-05) // returns something like:

{ day:'Saturday', date:'2010-01-05' },
{ day:'Sunday', date:'2010-02-05' },
{ 开发者_C百科day:'Monday', date:'2010-03-05' }[...]

Just the day of the first day of the month may (saturday, 01) and the last (monday, 31) would be great, too.


You can do this yourself pretty easily. The Javascript "Date" object is a great help for things like this:

function listDays(monthNumber) {
  var days = [],
    today = new Date(),
    d = new Date(today.getFullYear(), monthNumber, 1);

  while (d.getMonth() == monthNumber) {
    days.push({ "date": d.getDate(), "weekday": d.getDay()});
    d.setDate(d.getDate() + 1);
  }
  return days;
}

That only returns the days in the month numerically, but it'd be easy to extend with an array of day-of-week names:

function listDays(monthNumber) {
  var days = [],
    today = new Date(),
    d = new Date(today.getFullYear(), monthNumber, 1),
    weekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

  while (d.getMonth() == monthNumber) {
    days.push({ "date": d.getDate(), "weekday": weekdays[d.getDay()]});
    d.setDate(d.getDate() + 1);
  }
  return days;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜