Reputation: 1
I want to write a shell script which will accept
from user and will validate the date and time.
For Example:
./test.sh mmddyyyy hhmmss 12122012 121212
should return the correct result.
Upvotes: 0
Views: 686
Reputation: 84642
You can do what you are attempting by using either if
or case
statements along with expr
operators to parse and validate the input to the script. The key is to parse and put the date
and time
components of the input into a format that can be interpreted by date --date=""
. There are a number of approaches you can take. Below is a minimal example using your example input:
#!/bin/sh
[ "$#" -lt "4" ] && {
printf "error: insufficient input.\n"
printf "usage: %s datestr timestr date time\n" "${0//*\//}"
printf " eg: %s mmddyyyy hhmmss 01012011 122515\n" "${0//*\//}"
exit 1
}
datestr=
timestr=
case "$1" in
"mmddyyyy" )
[ $(expr length "$3") -ne "8" ] && {
printf "error: invalid date for format.\n"
printf " '%s' != '%s'\n" "$1" "$3"
exit 1
}
datestr="$(expr substr "$3" 1 2)"
datestr="$datestr/$(expr substr "$3" 3 2)"
datestr="$datestr/$(expr substr "$3" 5 4)"
;;
* ) printf "error: invalid date format '%s'\n" "$1"
;;
esac
case "$2" in
"hhmmss" )
[ $(expr length "$4") -ne "6" ] && {
printf "error: invalid time for format.\n"
printf " '%s' != '%s'\n" "$2" "$4"
exit 1
}
timestr="$(expr substr "$4" 1 2)"
timestr="$timestr:$(expr substr "$4" 3 2)"
timestr="$timestr:$(expr substr "$4" 5 2)"
;;
* ) printf "error: invalid time format '%s'\n" "$2"
;;
esac
printf "%s\n" "$(date -d "$datestr $timestr")"
exit 0
Example Use/Output
$ sh datetmstr.sh mmddyyyy hhmmss 12122012 121212
Wed Dec 12 12:12:12 CST 2012
You can build upon this approach to add additional date/time input formats. POSIX shell doesn't have the largest selection of string handling routines, but it has more than enough for this type of work.
Upvotes: 1
Reputation: 762
use this if you get 0 your date is valid
date "+%d/%m/%Y" -d "03/10/2016" > /dev/null 2>&1
is_valid=$?
Upvotes: 1