Difference in date time

前端 未结 3 443
梦毁少年i
梦毁少年i 2021-01-24 10:21

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

H

相关标签:
3条回答
  • 2021-01-24 11:00

    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
    
    0 讨论(0)
  • 2021-01-24 11:03
    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)
    
    0 讨论(0)
  • 2021-01-24 11:21

    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
    
    0 讨论(0)
提交回复
热议问题