Vedh
Vedh

Reputation: 93

How to split the time from hh:mm:ss to hh mm ss in unix?

My input is

 ./filename Apr 11 16 05:10:20 Jun 12 16 06:22:35

I want to convert Apr 11 16 05:10:20 to 16 04 11 05 10 20 I am using the following function,

convert_date_2() 
{
local months=( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec )
local i

for (( i=0; i<11; i++ ))
do
[[ $1 = ${months[$i]} ]] && break
done
printf "%2d %02d %02d %02d %02d %02d \n" $3 $(( i+1 )) $2 $4 $5 $6
}

Start=$( convert_date_2 $1 $2 $3 $4 )
Stop=$( convert_date_2 $5 $6 $7 $8 )
echo $Start;
echo $Stop;

But I am getting output like 16 04 11 05 00 00 and 16 06 12 06 00 00. I actually I want 16 04 11 05 10 20 and 16 06 12 06 22 35.

How can I modify this?

Upvotes: 1

Views: 181

Answers (2)

anubhava
anubhava

Reputation: 785651

You can change your code to this:

convert_date_2()  {
   local months='JanFebMarAprMayJunJulAugSepOctNovDec'
   local p="${months%$1*}"
   printf "%2d %02d %02d %s\n" $3 $(( ${#p} / 3 +1)) $2 "${4//:/ }"
}

start=$(convert_date_2 $1 $2 $3 $4)
stop=$(convert_date_2 $5 $6 $7 $8)
echo "start=$start"
echo "sop=$stop"

Code Demo

An example call to your new function:

convert_date_2 Apr 11 16 05:10:20
16 04 11 05 10 20

Upvotes: 1

sat
sat

Reputation: 14949

You can simply do it with date command itself.

date -d 'Apr 11 2016 05:10:20' '+%y %m %d %H %M %S'

Test:

$ date -d 'Apr 11 2016 05:10:20' '+%y %m %d %H %M %S'
16 04 11 05 10 20

$ var_date="Jun 12 2016 06:22:35"
$ date -d "$var_date" '+%y %m %d %H %M %S'
16 06 12 06 22 35

Note: Here, input date format have year as 2016 not 16.

Update:

Try this :

$ var_date="Jun 12 16 06:22:35"
$ date -d "$(echo $var_date | awk '$3="20"$3')" '+%y %m %d %H %M %S'

$ date -d "$(awk '$3="20"$3' <<< $var_date)" '+%y %m %d %H %M %S'

Upvotes: 7

Related Questions