I am using the date -d
command to change a specific date format to another.
Below is the example used
currDate=`Wed 12 Feb 2014`
formattedDate=`date -d"${currDate}" +%Y%m%d`
echo $formattedDate
You shouldn't use backticks (`
) unless you are assigning the result of a command to a variable, in this case you are assigning a string so you should just quote it:
currDate="Wed 12 Feb 2014"
formattedDate=`date -d"${currDate}" +%Y%m%d`
echo $formattedDate
I don't have access to a mac so I can't test this but according to the OSX date
man page, this should work:
formattedDate=`date -jf "%a %d %b %Y" "${currDate}" +%Y%m%d`
Many of the utilities in OSX are based on BSD versions of same so the info you find for Linux does not always translate to OSX. From man date
on OSX:
-f Use input_fmt as the format string to parse the new_date provided
rather than using the default [[[mm]dd]HH]MM[[cc]yy][.ss] format.
-j Do not try to set the date. This allows you to use the -f flag in
addition to the + option to convert one date format to another.
-d
which according to man is an option to specify dst. It needs -f
to specify input format but that is not working either.
%d
to %e
for example.
I tested the following on my OSX which worked:
currDate="Wed 12 Feb 2014"
formattedDate=`date -v"${currDate}" +%Y%m%d`
echo $formattedDate
From the manpage -v
is:
Adjust (i.e., take the current date and display the result of the adjustment; not actually set the date) the second, minute, hour, month day, week day, month or year according to val. If val is preceded with a plus or minus sign, the date is adjusted forwards or backwards according to the remaining string, otherwise the relevant part of the date is set. The date can be adjusted as many times as required using these flags. Flags are processed in the order given.
This will get the right answer:
date -jf"%a %e %b %Y" "Wed 12 Feb 2014" +%Y%m%d
The output is:
20140212
20140212
? If I read the man page correctly, it should just add to today's date unless you use -f
. "Take the current date"
-f
option either fiddling for 30 minutes now.
-f
and -j
.