Balualways
Balualways

Reputation: 4520

Check the date and time entered by user in UNIX

I have a Shell script which uses the date and time parameters entered by the user. Date as mm/dd/yyyy and Time as HH:MM . What would be the easiest means to check the user had entered the proper date [ like month should be less than 12.... for time MM should be less than 60... Do we have any built in functions in UNIX for checking the timestamp?

Upvotes: 4

Views: 11830

Answers (3)

slashmais
slashmais

Reputation: 7155

(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

Upvotes: 0

Joel
Joel

Reputation: 30166

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 2000
joel@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=$1
date -d "$usrdate"  > /dev/null 2>&1
if [ $? -eq 0 ]; then
        echo "Date $usrdate was valid"
else
        echo "Date $usrdate was invalid"
fi

Upvotes: 2

Raedwald
Raedwald

Reputation: 48702

You could use grep to check that the input conforms to the correct format:

if ! echo "$INPUT" | grep -q 'PATTERN'; then
   # handle input error
fi

where PATTERN is a regular expressino that matches all valid inputs and only valid inputs. I leave constructing that pattern to you ;-).

Upvotes: 0

Related Questions