Validate date format in a shell script

Use date

date "+%d/%m/%Y" -d "09/99/2013" > /dev/null  2>&1
 is_valid=$?

The date string must be in "MM/DD/YYYY" format.

If you do not get 0 then date is in invalid format.


The simplest solution, that still works perfectly, is the following :

if [[ $1 =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]] && date -d "$1" >/dev/null 2>&1
   ...

It consists in combining 2 checks :

  • the first part checks that $1 is of this format : NNNN-NN-NN
  • the second part checks that it is a valid date

You need the two checks because :

  • if you don't do the first check, date will exit with code 0 even if your variable is a valid date in another format
  • if you don't do the second check, then you can end up with a 0 even for variables such as 2016-13-45