Reputation: 318
I want to know how to use shell convert from 01/Mar/2011 to 2011-03-01 on OS X?
in my bash:
bash-3.2$ date -d "03 Mar 2011" +%F
usage: date [-jnu] [-d dst] [-r seconds] [-t west] [-v[+|-]val[ymwdHMS]] ...
[-f fmt date | [[[mm]dd]HH]MM[[cc]yy][.ss]] [+format]
Thank @ghoti, on OS X should use like:
date -j -f '%d %b %Y' "02 JUN 2011" '+%F'
Failed conversion of ``02 JUN 2011'' using format ``%d %b %Y''
date: illegal time format
usage: date [-jnu] [-d dst] [-r seconds] [-t west] [-v[+|-]val[ymwdHMS]] ...
[-f fmt date | [[[mm]dd]HH]MM[[cc]yy][.ss]] [+format]
but, my system show me > date +%b 7
, %b
is a number, not an abbreviated month name.
Thanks.
Upvotes: 1
Views: 1051
Reputation: 23
The idea is to convert date STRING to epoch time, then output it as the format you desire.
I tested it on Cygwin and CentOS.
convert date STRING to epoch time
use command 'date -d STRING +%s', STRING can be 01 Mar 2011 or 01-Mar-2011 or 01/03/2011
date -d '01 Mar 2011' +%s
1298908800
output epoch time to date format
use command 'date -d @EPOCH_TIME '+%Y-%m-%d'
date -d @1298908800 '+%Y-%m-%d'
2011-03-01
Because your date STRING 01/Mar/2011 is not a valid format for date -d, so you have to use 'sed' to convert it.
echo "01/Mar/2011"|sed -e 's/\// /g'
01 Mar 2011
So your solution can be
old_date="01/Mar/2011"
date_string=`echo "$old_date"|sed -e 's/\// /g'`
echo $date_string
01 Mar 2011
epoch_time=`date -d "$date_string" +%s`
echo $epoch_time
1298908800
date -d @$epoch_time '+%Y-%m-%d'
2011-03-01
Upvotes: 0
Reputation: 46856
Using BSD date, you can convert one format to another by using the -f
option.
For example, putting your input into a variable so you can see how to re-use this date command:
$ d="27 JUN 2011"
$ date -j -f '%d %b %Y' "$d" '+%F'
2011-06-27
You can man date
to see how everything works, but the basics are this;
-j
tells the command just to process input and not try to set your system clock.-f this that
uses this
as an input format to interpret that
.+yadda
uses the specified output format to print the interpreted date.For details on the input format, on OS X or most BSDs, you can man strftime
.
Upvotes: 1