convert date format YYYYMMDD to MM/DD/YYYY

In my shell script i have a variable which stores date in the format of YYYYMMDD. Is there any way to format this value to MM/DD/YYYY.

Thanks.

echo "YYYYMMDD" | awk '
BEGIN {OFS="/"}
{print substr($1,5,2), substr($1,7,2), substr($1,1,4)}'

Regards,
Tayyab

You have broken a rule by duplicating your thread. The other one is here - changing the format of date.

Using shell script.

#! /bin/ksh

format=YYYYMMDD

YEAR=${format%????}
DAY=${format#??????}
MON=${format#$YEAR}
MON=${MON%$DAY}
echo $MON/$DAY/$YEAR

Using sed.

echo "YYYYMMDD" | sed -n -e "s_\(....\)\(..\)\(..\)_\2/\3/\1_p"

Thank you.

hi all....

Want some clarification ..

In the below scripts ...

echo "YYYYMMDD" | awk 'BEGIN {OFS="/"}{print substr($1,5,2), substr($1,7,2), substr($1,1,4)}'

What is OFS..Also how does the '/' is placed inbetween..

Thanks in advance,
Arun....

OFS is Output Field Separator, I don't know the internal technicle details of awk though I can imagine that awk puts each print command in a stack like

print substr($1,5,2)
print substr($1,7,2)
print substr($1,1,4)

and then separates each output of print with an OFS if defined, default OFS is " " a whitespace. Hope it helps.

Regards,
Tayyab

hi nasirgondal,

I also wanted such a script. It works fine but if the date is not exactly in YYYYMMDD format, lets say YYYYMDD or YYYYMMD format its not working. Is there any solution even for this. Appreciate your help

#! /bin/ksh

format=YYYYMMDD

YEAR=${format%????}
DAY=${format#??????}
MON=${format#$YEAR}
MON=${MON%$DAY}
echo $MON/$DAY/$YEAR

What would be the following: 2008111?
Is it November 1, 2008
or January 11, 2008

My Dear,

You can use the below command and so on to get the date/time as you wish:

example 1:
date '+DATE: %m/%d/%y%nTIME:%H:%M:%S'

 generates as output

 DATE: 08/01/76

 TIME: 14:45:05

example 2:
date '+20%y/%m/%d'
2009/04/08