开发者

Check the date and time entered by user in UNIX

开发者 https://www.devze.com 2023-02-02 14:42 出处:网络
I have a Shell script which uses the date and time parameters entered by the user. Dateas mm/dd/yyyyand Time as HH:MM .

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 6开发者_JAVA技巧0... Do we have any built in functions in UNIX for checking the timestamp?


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


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 ;-).


(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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号