Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: How to convert a number into a month string?

Tags:

bash

I want to map, for example, 4 to 'Apr' (3 character abbrev of the name of the month)

like image 758
Anthony Kong Avatar asked Apr 11 '12 01:04

Anthony Kong


People also ask

What does $() mean in bash?

Example of command substitution using $() in Linux: Again, $() is a command substitution which means that it “reassigns the output of a command or even multiple commands; it literally plugs the command output into another context” (Source).

How do I print the month name in Linux?

Linux date Command Format Options %D – Display date as mm/dd/yy. %Y – Year (e.g., 2020) %m – Month (01-12) %B – Long month name (e.g., November)

What is date +% s in bash?

date +%S. Displays seconds [00-59] date +%N. Displays in Nanoseconds.

How do I change the date format in bash?

Bash Date format MM-DD-YYYY To format date in MM-DD-YYYY format, use the command date +%m-%d-%Y or printf "%(%m-%d-%Y)T\n" $EPOCHSECONDS .


2 Answers

A locale-sensitive result can be gained like this; put the number into the month-position of the date, passed as date to be output to date, and choose an arbitrary year and day (keep away from the 50ies and the far future, and avoid days much greater than 20). It hasn't to be the actual year:

i=10; date -d 2012/${i}/01 +%b

Here, with locale de_DE, I get as result:

Okt

(I didn't choose April, because it is the default for date to take the current month, so with a bad formatted -d -date, you get April, even if i=10. I know it, because I experienced it. And furthermore: The german name for April is April, so it wouldn't serve well as example for the finer details, which follow just now:)

i=10; LC_ALL=C date -d 2012/${i}/01 +%b

this reveals the month in an international standard style.

The advantage of the solution is, that it will survive revolutions, which rename the months to Brumaire, Obamer or internationalization attemps (Mär, Mai, Okt, Dez in German, i.e.).

like image 83
user unknown Avatar answered Oct 22 '22 06:10

user unknown


Try this :

MONTHS=(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)

echo ${MONTHS[3]}

Or as per @potong's suggestion (to have a 1-1 correspondence between month number and index)

MONTHS=(ZERO Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)

echo ${MONTHS[4]}
like image 43
Dr.Kameleon Avatar answered Oct 22 '22 06:10

Dr.Kameleon