Unix date formatting to include day suffix (st, nd, rd and th)

How to add suffix on day day of unix date?

I will explain. I have a snippit TextMate package that writes out today's date. It uses date and unix formatting. Here is the code:

`date +%A` `date +%d` `date +%B` `date +%Y`

It outputs:

Monday March 22, 2010

I would like to add a suffix to the day ( st , nd , rd and th ). So:

Monday, March 22, 2010

As far as I can see, there is no built-in function in unix date formatting, as in PHP (j). How can I achieve this in unix? Complex regular expression for the number of days?

+5
source share
2 answers

- Linux (Ubuntu 8.10). , Solaris, , , _, %, 0. 1 01 (01st doesn 't 1-).

( , , ) DaySuffix, . func , , , . 11, 12 13 - !

#!/bin/sh

DaySuffix() {
    if [ "x`date +%-d | cut -c2`x" = "xx" ]
    then
        DayNum=`date +%-d`
    else
        DayNum=`date +%-d | cut -c2`
    fi

    CheckSpecialCase=`date +%-d`
    case $DayNum in
    0 )
      echo "th" ;;
    1 )
      if [ "$CheckSpecialCase" = "11" ]
      then
        echo "th"
      else
        echo "st"
      fi ;;
    2 )
      if [ "$CheckSpecialCase" = "12" ]
      then
        echo "th"
      else
        echo "nd"
      fi ;;
    3 )
      if [ "$CheckSpecialCase" = "13" ]
      then
        echo "th"
      else
        echo "rd"
      fi ;;
    [4-9] )
      echo "th" ;;
    * )
      return 1 ;;
    esac
}

# Using consolidated date command from chris_l
# Also using %-d instead of %d so it doesn't pad with 0's
date "+%A %-d`DaySuffix` %B %Y"
+3

Try.

#!/bin/sh
DaySuffix() {
  case `date +%d` in
    1|21|31) echo "st";;
    2|22)    echo "nd";;
    3|23)    echo "rd";;
    *)       echo "th";;
  esac
}
date "+%A %d`DaySuffix` %B %Y"
+5

All Articles