0

I am looking to take a string as command parameter like HHMMSS and convert it to time format like HH:MM:SS and append it to current date (date needs to be generated within the script using 'date' command )

For example, if my command line argument will be 093500, this should be converted to 09:35:00 and be appended with current date like, 2018-05-16 09:35:00

Example:

$ ./convertTime.sh 093500
2018-05-16 09:35:00

2 Answers 2

4

If by ksh, you mean ksh93:

$ t=093500
$ DATEMSK=/dev/stdin <<<%H%M%S printf "%(%F %T)T\n" "$t"
2018-05-17 09:35:00

Or:

$ printf '%(%F)T %.8s\n' now "${t//??/\0:}"
2018-05-17 09:35:00

Or portably (shells of Bourne or csh families or fish)

$ date +"%Y-%m-%d $t" | sed 's/\(..\)\(..\)$/:\1:\2/'
2018-05-17 09:35:00

(for rc-like shells, use date +'%Y-%m-%d '$t instead)

0

Here's one possible solution. Works as so:

$ ./format_date.sh 092533
2018-05-17 09:25:33
#!/bin/bash

format_time(){
    point=0
    while [ "$point" -le "${#1}" ];
    do
        string=$string"${1:$point:2}"
        if [ "$point" -lt "$((${#1}-2))"  ]
        then
        string=$string":"
        fi
        point=$((point+2))
    done
    echo "$string"
}

echo "$(date +'%Y-%m-%d')" "$( format_time "$1" )"

This takes advantage of parameter substitution, typical of bash and ksh, so this suits your question tags, but it is not suitable for POSIX /bin/sh since ${variable:position:offset} form doesn't work in POSIX /bin/sh.

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .