0

I am completely new to shell scripting. I need to change the format of given date to customized format like i have date in a variable with format as MM/DD/YY HH:MM:SS but i want date in a format as MM/DD/YYY HH:MM:SS which is having four digits of the year. We can change the sys date format but i need the same in a variable. My code as below

START_DATE="12/20/14 05:59:01"
yr=`echo $START_DATE | cut -d ' ' -f1 | cut -d '/' -f3`
yr_len=`echo $yr | wc -c`
if [ $yr_len -lt 4 ]
then
    tmp_yr="20${yr}";
else
    1=1;
fi
ln=`echo $tmp_yr|wc -c`

After this i strucked in reframe the same date in wanted format.

Can some one please help me

Regards, Sai.

Darpan
  • 5,623
  • 3
  • 48
  • 80
  • See [this question](http://stackoverflow.com/questions/6508819/convert-date-formats-in-bash) for details on doing that. – dwcoder Feb 16 '15 at 09:15

2 Answers2

1

Using GNU date:

date -d'02/16/15 09:16:04' "+%m/%d/%Y %T"

produces

02/16/2015 09:16:04

which is what you want. See man date for details about the formatting, or this question for a number of great examples.

Community
  • 1
  • 1
dwcoder
  • 478
  • 2
  • 8
  • thanks for your reply. but when i use this command , i am getting some error as date: illegal option -- d – user3377882 Feb 16 '15 at 09:29
  • The `-d` option only works with GNU date. Are you working on Mac or GNU/Linux, or something else? – dwcoder Feb 16 '15 at 09:56
  • I am working in GMT. Not in GNU. Could you please suggest me anothe way – user3377882 Feb 16 '15 at 10:34
  • No, `GNU date` is the program, and it works fine with GMT times. What is your `date` program? You can see it if you type `date --version` – dwcoder Feb 16 '15 at 12:07
  • I didnt get my date program. I am getting the same result for given command as well. I entered as: date --version Tried with different combinations but no luck :( – user3377882 Feb 16 '15 at 12:52
  • No, type `date --version` on its own, so that you can see what version your `date` program is. It is the wrong version, you need to update it, or install the right one, as [this question](http://stackoverflow.com/questions/6508819/convert-date-formats-in-bash) mentioned. – dwcoder Feb 16 '15 at 13:27
0

One option may be using the date/time functions inside awk. Here is a oneliner:

echo '02/16/15 09:16:04' | sed 's\[/:]\ \g' | awk '{d0=$3+2000FS$1FS$2FS$4FS$5FS$6; d1=mktime(d0);print strftime("%m/%d/%Y %T", d1) }'

output is:

02/16/2015 09:16:04

You can find more strftime formats in https://www.gnu.org/software/gawk/manual/html_node/Time-Functions.html

Julio
  • 105
  • 1
  • 3