Calculate the number of days in a month

From CodeCodex

Implementations[edit]

Bash[edit]

month="$1"
if [ -z "$month" ] || [ ${#month} != 6 ]; then
    echo must specify yyyymm, e.g. $(date +%Y%m)
    exit 2
fi
year=${month:0:4}
month=${month:4:2}

echo $((
        (
            $(date -u -d "${year}-${month}-01 +1 month" +%s)
        -
            $(date -u -d "${year}-${month}-01" +%s)
        )
    /
        86400
))

If the above script were stored in a file called days_in_month, then you would invoke it as follows:

days_in_month yyyymm

For instance,

days_in_month 200402

would print the number of days in February 2004, which is 29.

C/C++[edit]

  ...

int numberOfDays;
if (month == 4 || month == 6 || month == 9 || month == 11)
  numberOfDays = 30;
else if (month == 2)
{ bool isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
  if (isLeapYear)
    numberOfDays = 29;
  else
    numberOfDays = 28;
}
else
  numberOfDays = 31;

Java[edit]

//this method returns the maximum number of days of the provided calendar object's month
//for example, passing a calendar object set to 12/12/2006 would return 31
static int daysInMonth(GregorianCalendar c) {
   return c.getActualMaximum(c.DAY_OF_MONTH);
}

Ruby[edit]

def days_in_month(year, month)
  case month
  when 4,6,9,11
    30
  when 2
    (year%4==0 && year%100!=0 || year%400==0) ? 29 : 28
  else
    31
  end
end

Seed7[edit]

The "time.s7i" library contains the daysInMonth function to calculate the number of days in a month for a given year:

writeln("Days in February 2004: " <& daysInMonth(2004, 2));

The definition of daysInMonth in the "time.s7i" library is:

const func integer: daysInMonth (in integer: year, in integer: month) is func
  result
    var integer: leng is 0;
  local
    const set of integer: monthsOfLength31 is {1, 3, 5, 7, 8, 10, 12};
  begin
    if month in monthsOfLength31 then
      leng := 31;
    else
      if month = 2 then
        if isLeapYear(year) then
          leng := 29;
        else
          leng := 28;
        end if;
      else
        leng := 30;
      end if;
    end if;
  end func;

VB.NET[edit]

'Create a calendar
Dim calendar As System.Globalization.Calendar = New System.Globalization.GregorianCalendar

'Ask the calendar
Dim DaysInMonth As Integer = calendar.GetDaysInMonth(2008, 1)

Visual Basic[edit]

'For current month...

MsgBox DateAdd("m", 1, Now) - Now

'For some other month (Example: June)

Dim FirstDate As Date
FirstDate = "01/06/2006"
MsgBox DateAdd("m", 1, FirstDate) - FirstDate

Another approach:

Dim mnth as Integer
Dim yr as Integer
yr = 2004
mnth = 2
MsgBox DateSerial(yr, mnth+1, 0) - DateSerial(yr, mnth, 0)