The thing is that the format supplied to date
command controls only the output, not the input (passed with the --date
option). One needs to supply some format which date
will understand. For example, one could manually replace the dash in the input with a space, prepend the current year/month and use this modified string for testing:
#!/usr/bin/env bash
#date/time string is passed as first argument
dtime=$1
#replace first occurrence of - in $dtime with space
#and prepend the current year/month/
#This will for example
#transform the input "12-10:12:11" to "2017/03/12 10:12:11", i.e.,
#into a format which `date` understands. The reason for this is
#to provide complete date specification, otherwise `date`
#would complain that the date is invalid.
s=$(date +'%Y/%m/')${dtime/-/ }
#feed the transformed input obtained in previous step to the
#`date` command and print the output in the required '%d-%H:%M:%S' format
x=$(date +'%d-%H:%M:%S' --date="$s" 2> /dev/null)
#finally, check if this formatted value equals the original input or not
if [ "${x}" != "${dtime}" ]
then
echo "$dtime is NOT a valid date format, use the d-H:M:S format"
exit 0
fi
echo $dtime