Unix convert Month name to number

You can convert the month to a number by finding the position of the name string:

#!/bin/bash

month=Oct
months="JanFebMarAprMayJunJulAugSepOctNovDec"
tmp=${months%%$month*}
month=${#tmp}
monthnumber $((month/3+1))
printf "%02d\n" $monthnumber

The output of the script above is:

10

Your specific string you could code:

#!/bin/bash

mydate="Oct 2011"

monthnumber() {
    month=$1
    months="JanFebMarAprMayJunJulAugSepOctNovDec"
    tmp=${months%%$month*}
    month=${#tmp}
    monthnumber=$((month/3+1))
    printf "%02d\n" $monthnumber
}

arr=(`echo ${mydate}`);
month=$(monthnumber ${arr[0]})
year=$(echo ${arr[1]})
echo "$year-$month"

The output would be:

2011-10

read mon year <<< "Oct 2012"
date -d "$mon 1 $year" "+%Y-%m"

Result:

2012-10

mydate="Oct 2011"
date --date="$(printf "01 %s" $mydate)" +"%Y-%m"

The parse_datetime interface for GNU date (which is what the example uses) has lots of rules. the Oct 2011 form of the date isn't one of them, so you prepend a "01 " to the front of it and date likes it.

Tags:

Unix

Shell

Awk