• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 393
  • Last Modified:

retrive date in unix

I need to know if there is a function in unix where I pass a number and in return should get the month as a output  like if I pass 01  the return should be jan and 02 it should be feb etc
Is there any already built in function or any simple user defined function I can use etc?
0
welcome 123
Asked:
welcome 123
  • 2
1 Solution
 
woolmilkporcCommented:
If you have GNU date just run

date -d "01/01" "+%b"

The first "01" is the one which counts, the remainder ("01" in my example) can be freely chosen between "01" and "28".

Without GNU date you'll need a small script to achieve what you desire:

 echo "01" |awk '{split("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec",A," "); print A[$1+0]}'
0
 
woolmilkporcCommented:
A bash/ksh function embedded in an example script:
#!/bin/bash
function convmon {
 if RESULT=$(date -d "$1/01" "+%b" 2>/dev/null)
    then echo $RESULT
     else
       RESULT=$(awk -v N=$1 '
                BEGIN {split("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec",A," "); print A[+N+0]}
                            ')
         echo $RESULT
 fi
}

if [ $1 -gt 0 -a $1 -le 12 ]
   then NUMMON=$1
    else
     echo "Invalid Argument $1. Allowed 01..12." >&2; exit 22
fi
CHARMON=$(convmon $NUMMON)
echo $CHARMON

Open in new window

It will work with or without GNU date being available.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now