Hay everyone,
i want to Implement a dat2iso command as a script or as an alias, which accepts a date in German format DD.MM.YYYY as a parameter and outputs the date in ISO format YYYYMMDD as output (on stdout). Examples (as an alias or as a script in the system path;
outputs:
$ dat2iso 30.09.2021
20210930
$ dat2iso 01.01.2022
20220101
$ dat2iso 03/10/2021
Error! <-- Because the separator was. required.
$ dat2iso 03.10.21
Error! <-- Because the year YYYY was prescribed with four digits.
$ dat2iso 32.09.2021
Error! <-- Denn einen 32. gibt es nicht.
$ dat2iso 30.13.2021
Error! <-- Because there is no 13th month.
i have come sofar to change the formate but i cant figure the rest but im still working on it:
echo 30.09.2021 | awk -F '.' {'printf "%s%s%s\n",$3,$2,$1'}
CodePudding user response:
This should achieve what you expected :
#!/bin/bash
dat2iso(){
if [[ $1 =~ ^([[:digit:]]{2})\.([[:digit:]]{2})\.([[:digit:]]{4})$ ]]; then
local date="${BASH_REMATCH[3]}${BASH_REMATCH[2]}${BASH_REMATCH[1]}"
if date -d "$date" >& /dev/null; then
echo "$date"
else
echo "Invalid date value [$date]" >&2
fi
else
echo "Invalid format of input [$1]. Correct format [DD.MM.YYYY]" >&2
fi
}
dat2iso 30.09.2021
CodePudding user response:
A very verbose solution, but it checks for your given exemptions:
cat << EOF > dat2iso
#!/bin/bash
if [[ "\$1" == "" ]];then echo -e "NO INPUT. Exiting."; exit 1 ;fi
echo \$1 | awk -F '.' '/\//{ print "Input Error."; exit(1) }
\$1>31{ print "Too many days."; exit(1) }
\$2>12{ print "Too many months."; exit(1) }
\$3!~/[[:digit:]][[:digit:]][[:digit:]][[:digit:]]/{ print "Not enough year digits."; exit(1) }
{ print \$3\$2\$1 }'
EOF
chmod x dat2iso
$ ./dat2iso 09.12.2021
20211209