Some useful macOS date formatting and manipulation snippets

This isn’t an exhaustive list, just a handful of date-related snippets I use in scripts.

Month name to integer

When you need to convert a month name to its integer representation (e.g. ‘April’ → 04):

#!/bin/bash

month="April"
numeric_month=$(date -j -f "%b" "$month" "+%m" 2>/dev/null)
if [ -n "$numeric_month" ]; then
    echo "$numeric_month"
else
    echo "Invalid month abbreviation"
fi

# prints "04"``

It also works with abbreviated months like “Apr”.

If you have gdate installed, then it’s easier:

gdate -d "Apr" +%m

# prints "04"

Month integer to name

If gdate is installed:

#!/bin/bash

month2name() {
    gdate -d "2023-$1-01" +"%b"
}

month2name 04 # prints "Apr"

If you didn’t have gdate then this:1

#!/bin/bash

month2name() {
    local month_num="$1"
    case "$month_num" in
        01) echo "Jan" ;;
        02) echo "Feb" ;;
        03) echo "Mar" ;;
        04) echo "Apr" ;;
        05) echo "May" ;;
        06) echo "Jun" ;;
        07) echo "Jul" ;;
        08) echo "Aug" ;;
        09) echo "Sep" ;;
        10) echo "Oct" ;;
        11) echo "Nov" ;;
        12) echo "Dec" ;;
        *) echo "Invalid month number" ;;
    esac
}

month2name 04 # prints "Apr"

If you want the full month name and you’re using gdate:

#!/bin/bash

month2name() {
    gdate -d "2023-$1-01" +"%B"
}

month2name "Apr" # prints "April"

  1. Maybe something simpler could be done. Contact me if you know of anything. ↩︎