Tuesday, September 15, 2015

Date time stamps in bash with ordinal indicator

Update (Wednesday, 4th of November 2015, 12:15:35 AM): added link to more complicated script.

Date time stamps are easy in bash:

> echo $(date +"%Y%m%d_%H%M%S")

But I want more friendly date time stamps, like Tuesday, 15th of September 2015, 09:54:42 PM.

I found an algorithm that Greg Mattes wrote in this StackOverflow answer for Java. Here it is in bash:

n=$(date +"%d")

if [ $n -ge 11 -a $n -le 13 ] ; then
  echo "th"
 case $(( $n%10 )) in
   echo st
   echo nd
   echo rd
   echo th

So now I can do:

> echo $(date +"%A, %d`dateOrdinal.sh` of %B %Y, %I:%M:%S %p")
Tuesday, 15th of September 2015, 09:57:53 PM

Here is a more complicated version of this script that will accept a date, a date format and output formatted date where you can use %O as a placeholder for the ordinal in the format: http://pastebin.com/xZ1afqqC.