Check the date and time entered by user in UNIX
You could use the unix date tool to parse and verify it for you, and test the return code e.g.
A valid date, return code of 0:
joel@bohr:~$ date -d "12/12/2000 13:00"Tue Dec 12 13:00:00 GMT 2000joel@bohr:~$ echo $?0
An invalid date, return code 1:
joel@bohr:~$ date -d "13/12/2000 13:00"date: invalid date `13/12/2000 13:00'joel@bohr:~$ echo $?1
You can vary the input format accepted by date by using the +FORMAT option (man date)
Putting it all together as a little script:
usrdate=$1date -d "$usrdate" > /dev/null 2>&1if [ $? -eq 0 ]; then echo "Date $usrdate was valid"else echo "Date $usrdate was invalid"fi
You could use grep
to check that the input conforms to the correct format:
if ! echo "$INPUT" | grep -q 'PATTERN'; then # handle input errorfi
where PATTERN is a regular expressino that matches all valid inputs and only valid inputs. I leave constructing that pattern to you ;-).
(Late answer)
Something that you can use:
...DATETIME=$1#validate datetime..tmp=`date -d "$DATETIME" 2>&1` ; #return is: "date: invalid date `something'"if [ "${tmp:6:7}" == "invalid" ]; then echo "Invalid datetime: $DATETIME" ;else ... valid datetime, do something with it ...fi