Check the date and time entered by user in UNIX
11,708
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
Author by
Balualways
Linux Enthusiast and explorer, Loves automation and Continuous Delivery, hiking, scripting and vodka
Updated on August 12, 2022Comments
-
Balualways almost 2 years
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?