Converting date DD MM YYYY to DD MON YYYY

Hello,

I am writing a script that parses different logs and produces one. In the source files, the date is in DD MM YYYY HH24:MI:SS format. In the output, it should be in DD MON YYY HH24:MI:SS (ie 25 Jan 2010 16:10:10)
To extract the dates, I am using shell substrings, i.e.:

read line
 
year=${line:8:4}
month=${line:5:2}
day=${line:2:2}
hour=${line:13:2}
min=${line:16:2}
sec=${line:19:2}
 
echo "$year$month$day$hour$min$sec" # prints something like 20110325161610 (I use this numeric value to compare it agains reference date, i.e. date when this script ran last time)
 
if [ "$year$month$day$hour$min$sec" -gt "$lastlog" ]
then
  # output date in DD MON FORMAT... how?
fi

Of course I can do a routine like: if mon = 01 then mon = 'JAN', if mon = 02 then mon = 'FEB'... But I guess there must be a nicer solution to this. Maybe solution that will take into account also LANG setting (not a requirement, but would like to have it).

Maybe date function can be used for that, but I did not figure out how to pass the -d parameter (what format should it be in?). Did not find much in FAQ: Date Arithmetics either :frowning:

You can give this a try:

MON=$(echo "$month" | awk '
{
  split("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec", month, " ")
  for (i=1; i<=12; i++) mdigit[month]=i
  print month[$0]
}')

Oops, haven't read the last line of the 1st post..(-d option). Anyway this could be helpful for users of the date function without the -d option.

Try this:

date +'%d %b %Y %H:%M:%S' -d "$year$month$day $hour:$min:$sec"

Dahu: thank you, that was helpful.

Is there a way to do it the other way round as well? That means from i.e. 26 Mar 2011 get 20110326?

Tried the following, but not much success. Does date really only accept date in YYYYMMDD format?

date +'%d %m %Y %H:%M:%S' -d "2011Mar26"
date +'%d %m %Y %H:%M:%S' -d "26 Mar 2011"

the 2nd attempt looks OK, except your format is wrong, All these worked for me:

date -d "26 Mar 2011" +'%Y%m%d' 
date -d "Mar 26 2011" +'%Y%m%d' 
date -d "Mar-26-2011" +'%Y%m%d' 
date -d "26-Mar-2011 00:00" +'%Y%m%d'