Convert Month Number to Month Name

40,016

Solution 1

if you only need to map a few keys to values , just use an array

#!/bin/ksh

## cmdline argument is e.g. "2003-10-22"
DATE=$1

### extract day, month and year into separate variables
MONTHDAY=${DATE#*-}

YEAR=${DATE%%-*}
MONTH=${MONTHDAY%%-*}
DAY=${MONTHDAY#*-}

# an array to look up th month-names
# since month-numbers start with 1, the first element in the array is invalid.
set -A monthnames invalid Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec

## perform the lookup
MONTHNAME=${monthnames[${MONTH}]}

## display "<Month> <DAY>"
echo ${MONTHNAME} ${DAY}

Solution 2

With a recent enough version of ksh:

$ printf "%(%a %b %d %Y)T\n" 2013-10-22
Tue Oct 22 2013

(note that it is locale aware, in a Spanish locale for instance, it will output mar oct 22 2013)

Solution 3

GNU date:

$ date -d 2013-10-22 '+%b %-d'
Oct 22

OS X and FreeBSD date:

$ date -jf %F 2013-10-22 '+%b %-d'
Oct 22

%b is an abbreviated month name and %B is a full month name.

Share:
40,016
peja11
Author by

peja11

Updated on September 18, 2022

Comments

  • peja11
    peja11 over 1 year

    is there a way to convert month number to name?

    example:

    2013-10-22 will become Oct 22

    I don't have the GNU date and my OS is AIX.

  • Colin 't Hart
    Colin 't Hart over 2 years
    NB This returns locale-specific month names. I was wondering why in my case it was returning an all-lowercase month abbreviation until I ran it with %B and got the month name in my locale. I ended up using LC_NAME=en_US date -d 1980-03-01 '+%b' to force English month names.