Shell Script to find the validity of a given date

in Categories Time and Date last updated April 5, 2008

Date is entered in mm/dd/yyyy format using a keyboard. Various conditions are applied to make sure date is valid. Read the program comments to get idea about program logic.

#!/bin/bash
# Shell program to find the validity of a given date
# -----------------------------------------------
# Copyright (c) 2005 nixCraft project <http://cyberciti.biz/fb/>
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# -------------------------------------------------------------------------
 
# store day, month and year
dd=0
mm=0
yy=0
 
# store number of days in a month
days=0
 
# get day, month and year
echo -n "Enter day (dd) : "
read dd
 
echo -n "Enter month (mm) : "
read mm
 
echo -n "Enter year (yyyy) : "
read yy
 
# if month is negative (<0) or greater than 12 
# then it is invalid month
if [ $mm -le 0 -o $mm -gt 12 ];
then
    echo "$mm is invalid month."
    exit 1
fi
 
# Find out number of days in given month
case $mm in 
    1) days=31;;
    2) days=28 ;;
    3) days=31 ;;
    4) days=30 ;;
    5) days=31 ;;
    6) days=30 ;;
    7) days=31 ;;
    8) days=31 ;;
    9) days=30 ;;
    10) days=31 ;;
    11) days=30 ;;
    12) days=31 ;;
    *) days=-1;;
esac
 
# find out if it is a leap year or not
 
if [ $mm -eq 2 ]; # if it is feb month then only check of leap year
then
	if [ $((yy % 4)) -ne 0 ] ; then
	   : #  not a leap year : means do nothing and use old value of days
	elif [ $((yy % 400)) -eq 0 ] ; then
	   # yes, it's a leap year
	   days=29
	elif [ $((yy % 100)) -eq 0 ] ; then
	   : # not a leap year do nothing and use old value of days
	else
	   # it is a leap year
	   days=29
	fi
fi
 
# if day is negative (<0) and if day is more than 
# that months days then day is invaild
if [ $dd -le 0 -o $dd -gt $days ];
then
    echo "$dd day is invalid"
    exit 3
fi
 
# if no error that means date dd/mm/yyyy is valid one
echo "$dd/$mm/$yy is a vaild date"

Share this on:

2 comment

  1. try this code:

    DATE=”$*”

    [[ “${DATE}” != @(((([123][0]|[012][1-9])|3[1])?([ /.-])(0[13578]|1[02])?([ /.-])(19|20)[0-9][0-9])|(([123][0]|[012][1-9])?([ /.-]) (0[469]|11)?([ /.-])(19|20)[0-9][0-9])|(([12][0]|[01][1-9]|2[1-8])?([ /.-])02?([ /.-])(19|20)[0-9][0-9])|(29?([ /.-])02?([ /.-]) (19|20(0[48]|[2468][048]|[13579][26])))) ]] && echo error || echo good

  2. It’s both simpler and more reliable to use GNU date:

    #/bin/bash
    if [ “$( date -d “$1″ +%F 2>&1 | grep invalid )” = “” ] ; then echo “$1 is a valid date”; fi

    Have a question? Post it on our forum!