Number of days in a given month

October 30th, 2006

Chris F.A. Johnson describes in this Tuesday tip how to find the number of days in a given month. Chris is a UNIX genius, but I think there is a much easier way. Why not use the cal command? Its available on every System I have tried to use. AIX, Solaris, and many different flavors of Linux:

January:

root@www:~ # cal 1 `date +%Y` | egrep -v '[A-Za-z]' | wc -w
31

February:

root@www:~ # cal 2 `date +%Y` | egrep -v '[A-Za-z]' | wc -w
28

The following is equivalent (and much simpler) to Chris’s:

days_in_month() { ## USAGE: days_in_month [month [year]]
 if [ -n "$1" ]
 then
  dim_m=$1
  dim_y=$2
 else
  eval `date "+dim_m=%m dim_y=%Y"`
 fi
 _DAYS_IN_MONTH=`cal $dim_m $dim_y | egrep -v '[A-Za-z]' | wc -w`
}

I prefer a different method of programming. If the function echos the result, it can be assigned to a variable like so, days=$( days_in_month ). The following function is how I would write it:

days_in_month() { ## USAGE: days_in_month [month [year]]
  if [ -n "$1" ]
  then
  dim_m=$1
  dim_y=$2
  else
  eval `date "+dim_m=%m dim_y=%Y"`
  fi
  echo `cal $dim_m $dim_y | egrep -v '[A-Za-z]' | wc -w`
}

The reason I prefer this method is that I do not like setting variables and then using the variable name after running the function. There are alot of reasons, not the least of which is that you have remember both the function name and the variable(s) that it sets. Much too complicated for me.

One Response to “Number of days in a given month”

  1. Redy Says:

    More simple. With GNU version of date you dont ned cal. Use: date -d “$MONTH/01/$YEAR +1month -1day” +%d

    days_in_month() {
    if [ $# -gt 1 ]; then
    dim_y=$2
    dim_m=$1
    else
    if [ $# -eq 1 ]; then
    eval `date “+dim_y=%Y”`
    dim_m=$1
    else
    eval `date “+dim_m=%m dim_y=%Y”`
    fi
    fi
    date -d “$dim_m/01/$dim_y +1month -1day” +%d
    }

Leave a Reply

If Wordpress eats your comment (shell output, loops, ex..) email the text to me.