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

I want to match, for example, from 4 to 'Apr' (3 characters of the abbreviation on behalf of the month)

+6
source share
3 answers

Try the following:

MONTHS=(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec) echo ${MONTHS[3]} 

Or as suggested by @potong (have a 1-1 match between month number and index)

 MONTHS=(ZERO Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec) echo ${MONTHS[4]} 
+16
source
 #! /bin/bash case $1 in [1-9]|1[0-2]) date -d "$1/01" +%b ;; *) ; exit 1 esac 
+12
source

A locally sensitive result can be obtained in this way; put the number in the month-position of the date that has passed as the date that will be displayed to date, and choose an arbitrary year and day (stay away from the 50s and the distant future and avoid days that are much more than 20). This should not be the actual year:

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

Here, with locale de_DE, I get the result:

 Okt 

(I did not select April because it is the default value for the date for the current month, so with a poorly formatted -d -date you get April, even if I = 10. I know this because I experienced it. Also: German the name of April is April, so it will not serve as an example for more subtle details that are being followed just now :)

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

it shows a month in international standard style.

The advantage of the solution is that it will survive the revolutions that rename the months Brummers, Obama or internationalization (Mรคr, Mai, Okt, Dez in German, i.e.).

+4
source

Source: https://habr.com/ru/post/912892/


All Articles