如何在bash中转换两个日期时间的日期格式? [英] How to convert date format for two datetime in bash?

查看:222
本文介绍了如何在bash中转换两个日期时间的日期格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have to convert the datetime from "Apr 10 16 07:03:04" format to "\[10\/12\/16 07:03:04 BST]" format. I am using the following function.

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]

但是我得到如下输出, p>

But I am getting the following output like,

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

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

How to get the exact output? Please Help.

推荐答案

我会写这样的功能:

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):

Output (if your local time is BST):

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

这篇关于如何在bash中转换两个日期时间的日期格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆