Difference in date time

2019-03-01 13:58发布

I have 2 variables.

GMDCOMTM which stores the date time Tue Oct  1 13:32:40 2013
GMDRRSTM which stores the date time Tue Oct  2 23:35:33 2013

How do I calculate the difference between the 2 variables in hh:mm:ss format and store it in 3rd variable.? I dont want to use AWK, SED or PERL. I want to use simple shell script to do it.

标签: shell
3条回答
Summer. ? 凉城
2楼-- · 2019-03-01 14:12

Convert dates to %s ---> seconds since 1970-01-01 00:00:00 UTC.

$ date -d"Tue Oct  2 23:35:33 2013" "+%s"
1380749733

So the thing is to get the difference in seconds between both dates using bc as calculator:

$ d1="Tue Oct  1 13:32:40 2013"
$ d2="Tue Oct  2 23:35:33 2013"
$ echo $(date -d"$d2" "+%s") - $(date -d"$d1" "+%s") | bc
122573

Then you can get it into hours, days, with the great function Stéphane Gimenez indicates in UNIX & Linux:

$ displaytime 122573
1 days 10 hours 2 minutes and 53 seconds
查看更多
forever°为你锁心
3楼-- · 2019-03-01 14:27
C=$(date -d "Tue Oct  1 13:32:40 2013" +%s)
R=$(date -d "Tue Oct  2 23:35:33 2013" +%s)
T=$(date --date=@$((R-C))  +%H:%M:%S)
查看更多
孤傲高冷的网名
4楼-- · 2019-03-01 14:30

I'm normal using a custom made function to do the calculations. It may be long way but it will definitely work on all UNIX and Linux based systems. Following the code block.

time_diff(){
    foodate1=$1
    foodate2=$2
    foosecvall=`echo $foodate1 | awk -F: '{ print ($1 * 3600) + ($2 * 60) + $3 }'`
    foosecval2=`echo $foodate2 | awk -F: '{ print ($1 * 3600) + ($2 * 60) + $3 }'`
    foodiffsec=$((foosecvall-foosecval2));

    s=$foodiffsec
    h=$((s/3600));
    s=$((s-$((h*3600))));
    m=$((s/60));
    s=$((s-$((m*60))));
    footmstm=$h":"$m":"$s
}

Place the above code in your script and then call the function like follows.

TIME1="10:12:14"
TIME2="12:15:14"

time_diff $TIME2 $TIME1

echo $footmstm
查看更多
登录 后发表回答