如何在bash中转换两个日期时间的日期格式?

时间:2016-06-28 07:54:28

标签: bash datetime unix sed

我必须将日期时间从"Apr 10 16 07:03:04"格式转换为"\[10\/12\/16 07:03:04 BST]"格式。我正在使用以下功能。

convert_date () {
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]} ]] && [[ $5 = ${months[$i]} ]] && break
done
printf "\[%2d\/%02d\/%02d $4 BST]\n" $2 $(( i+1 )) $3
printf "\[%2d\/%02d\/%02d $8 BST]\n" $6 $(( i+1 )) $7    
}

d=$( convert_date $1 $2 $3 $4 )
e=$( convert_date $5 $6 $7 $8 )
echo $d
echo $e

我的输入将是

./date.sh Apr 10 16 07:03:04 May 12 16 08:11:09

我的输出应该是

\[10\/12\/16 07:03:04 BST]
\[12\/12\/16 08:11:09 BST]

但我得到以下输出,如

\[10\/12\/16 07:03:04 BST] \[12\/00\/00 BST]
\[12\/12\/16 08:11:09 BST] \[12\/00\/00 BST]

如何获得准确的输出?请帮助。

2 个答案:

答案 0 :(得分:2)

我会写这样的函数:

function convert_date() {

    # First sanitize input to something the date command can understand
    # The problem here is just the 16 which should be 2016
    input="$(awk -v year="$(date +%Y)" '{$3=year}1' <<< ${1})"

    # Now use the date command to reformat the string
    date -d"${input}" +'[%d/%m/%y %H:%M:%S %Z]'
}

这样称呼:

convert_date 'Apr 10 16 07:03:04'

输出(如果您的当地时间是BST):

[10/04/16 07:03:04 BST]

答案 1 :(得分:-1)

你的方法看起来很不寻常,我可能会使用date而不是脚本。但是如果删除第二个printf,输出似乎与您预期的格式相符。我不确定为什么它首先出现在那里。