Extract date from a variable in a different format

I assume you are talking about Bash. If so, then you are missing the " around the arguments of the --date parameter.

Instead of

a=`date --date=$Prev_date '+%y/%m/d'`

try this

a=`date --date="$Prev_date" '+%y/%m/d'`

and I'm guessing the d is supposed to have a %. So then it would be like that:

a=`date --date="$Prev_date" '+%y/%m/%d'`

The reasons why your error showed you the usage of the date command is following:

Without the " around $Prev_date, the variable will be substituted and the command looks like this:

a=`date --date=Wed Dec 25 06:35:02 EST 2013 '+%y/%m/d'`

So only the Wed is taken as argument to --date, while all the other parts of the $Prev_date string are considered separate parameters to the date command. So date says it doesn't know a parameter called Dec and shows you it's help output.


The -d option is GNU specific.

Here, you don't need to do date calculation, just rewrite the string which already contains all the information:

a=$(printf '%s\n' "$Prev_date" | awk '{
  printf "%04d-%02d-%02d\n", $6, \
  (index("JanFebMarAprMayJunJulAugSepOctNovDec",$2)+2)/3,$3}')

If I understand right, you want to save the date, so that you can reuse it later to print the same date in different formats. For this, I propose to save the date in a format that can be easily parsed by the date -d command, and let the date command do the formatting.

As far as I know, the format +%Y%m%d %H:%M:%S is the most platform independent. So let's save the date in this format:

d=$(date '+%Y%m%d %H:%M:%S')

Then later you can print this date in different formats, for example:

$ date +%c -d "$d"
Tue 31 Dec 2013 01:13:06 PM CET
$ date +'Today is %A' -d "$d"
Today is Tuesday
$ date +'Today is %F' -d "$d"
Today is 2013-12-31

UPDATE

If you are given a date string like Wed Dec 25 06:35:02 EST 2013, then you can try to parse it with date -d and change its format, for example:

$ date +%F -d 'Wed Dec 25 06:35:02 EST 2013'
2013-12-25

This works with GNU date. If it doesn't work in your system, you can try the gdate command instead, usually it exists in modern systems.

Tags:

String

Shell

Date