Reputation: 73
Is there a way to check if a date argument is in the correct date range eg
2016-10-32 or 2016-09-31 should display as invalid
.
i can able to find correct argument yyyy-mm-dd using below code
if [[ $1 =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]]
then echo "Date $1 is in valid format (YYYY-MM-DD)"
else echo "Date $1 is in an invalid format (not YYYY-MM-DD)"
fi
How to check date is in correct date range
Upvotes: 1
Views: 1184
Reputation: 246744
Echoing karakfa's advice to use GNU date for the validation. Showing how to check the date is in a range using simple lexical comparison
#!/bin/bash
date=$1
start="2016-05-01"
end="2016-09-01"
ymd=$(date -d "$date" +%F) || exit 1
# unfortunately, bash does not have a "<=" operator for strings
if [[ ($start < $ymd || $start = $ymd) && ($ymd < $end || $ymd = $end) ]]; then
echo "$date in range"
else
echo "$date not in range"
fi
As we see, date
is very liberal about what it accepts
$ bash datecheck.sh "sept 1"
sept 1 in range
$ bash datecheck.sh "sept 2"
sept 2 not in range
$ bash datecheck.sh "sept 31"
date: invalid date ‘sept 31’
Upvotes: 0
Reputation: 67467
delegate the validity check to date
change the messages as you like
$ d='2016-10-32'; if date -d "$d" &>/dev/null; then echo "$d is OK"; else echo "$d is incorrect"; fi
2016-10-32 is incorrect
$ d='2016-10-31'; if date -d "$d" &>/dev/null; then echo "$d is OK"; else echo "$d is incorrect"; fi
2016-10-31 is OK
Upvotes: 1