Friday, February 11, 2011

Last day of the month, number of days in a month Linux shell bash script, date command in Unix

Number of days in a month is not inbuilt command in linux, In order to get the number of days in a month, we create a new date string of the first day of the next month and then go back to previous day which gives us the last day or number of days in the current month.


Lets say “di” is the date in format YYYYMMDD
di=20100101

Then you can derive the following

#Current date
DD=`date -d "${di}" +%F`

#Current day
dd=`date -d "${di}" +%d`
#Current month
mm=`date -d "${di}" +%m`
#Current year
yy=`date -d "${di}" +%Y`

#Next day
ddf=`date -d "${di} 1 day" +%d`
#Next month
mmf=`date -d "${di} 1 month" +%m`
#Next year
yyf=`date -d "${di} 1 years" +%Y`

#Previous day
ddp=`date -d "${di} -1 day" +%d`
#Previous month
mmp=`date -d "${di} -1 month" +%m`
#Previous year
yyp=`date -d "${di} -1 years" +%Y`

#Julian date
jd=`date -d "${di}" +%j`

#Number of days in month
dmp=$yy$mmf"01"
nd=`date -d "${dmp} -1 day" +%d`

Leave your comment if there is a better way to do it. Some people use calendar command to do it.

No comments:

Post a Comment