Checking if a variable is a date with the correct format

I would like to check if the variable is a date (not a problem), but if the variable has the correct date format (yyyy-MM-dd).

I tried:

export DATE_REFRESH=01/01/1900

if ! date -d $DATE_REFRESH "+%Y-%m-%d"; then
    echo "$DATE_REFRESH is not a valid date. Expected format is : yyyy-MM-dd"
fi

      

But that won't work.

I can try:

if [[ $DATE_REFRESH == [0-9][0-9][0-9][0-9]-[0-1][0-9]-[0-3][0-9] ]]

      

But I don't want to have a date before 33/19/2000 ...

+3


source to share


2 answers


You can use this snippet:

isValidDate() {
   if [[ "$1" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]] && date -d "$1">/dev/null 2>&1; then
      echo "valid"
   else
      echo "invalid"
   fi;
}

      



Testing:

isValidDate "1900-12-25"
valid

isValidDate "1900-14-25"
invalid

isValidDate "01/01/1900"
invalid

      

+4


source


You have to do both tests because a line date

can be everything, see the man page:

... -date = STRING is basically a free human readable format. a string such as ...



Use this:

if ! [[ "$DATE_REFRESH" =~ ^[[:digit:]]{4}-[[:digit:]]{2}-[[:digit:]]{2}$ ]] \
|| ! date -d $DATE_REFRESH >/dev/null 2>&1; then
  echo "$DATE_REFRESH is not a valid date. Expected format is : yyyy-MM-dd"
fi

      

+2


source







All Articles