Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if variable is a date with the correct format [duplicate]

Tags:

date

bash

I would like to test if a variable is a date (not a problem), but if the variable have 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 it doesn't work.

I can try with this :

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 to 33/19/2000...

like image 882
BnJ Avatar asked Dec 03 '25 17:12

BnJ


1 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
like image 58
anubhava Avatar answered Dec 06 '25 12:12

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!