I have some scripts that take a date as an optional parameter. It's now becoming necessary to actually do some sanity checking on that date as it is required to be in a strict format. I've come up with the following pretty quick, but wonder if you guys have anything like this or a more clever way. The following does check for future dates and invalid dates such as Feb 29 on non-leap year.
Code:
#!/bin/env bash
shopt -s -o nounset
DDMMYY=${1-'today'}
HHMMSS=${2-'09:00'}
# Returns:
# 0 - valid date
# 1 - Future date
# 2 - Invalid date
check_date()
{
{ DATE="`date -d "$1 $2" +%s`" || return 2
NOW="`date +%s`"
} >>/dev/null 2>&1
[[ "$DATE" -lt "$NOW" ]] && return 0 || return 1
}
# Returns:
# Exit code of `date`
# Sets FMT_DATE to formatted date "DD-Mon-YY HH:MM:SS"
get_fmt_date()
{
FMT_DATE="`date -d "$1 $2" +"%d-%b-%y %T"`"
return $?
}
check_date $DDMMYY $HHMMSS || exit $?
get_fmt_date $DDMMYY $HHMMSS
echo $FMT_DATE
Example usage:
Code:
[jc@centosvm ~]$ ./test_date.sh
30-Jul-08 09:00:00
[jc@centosvm ~]$ ./test_date.sh 2/29/08
29-Feb-08 09:00:00
[jc@centosvm ~]$ ./test_date.sh 2/29/08 1031
[jc@centosvm ~]$ ./test_date.sh 2/29/08 10:31
29-Feb-08 10:31:00
[jc@centosvm ~]$ ./test_date.sh 2/29/09
[jc@centosvm ~]$