Bash – Subtract time using bash

arithmeticbashdatevariable

Is it possible to use bash to subtract variables containing 24-hour time?

#!/bin/bash
var1="23:30" # 11:30pm
var2="20:00" # 08:00pm

echo "$(expr $var1 - $var2)"

Running it produces the following error.

./test 
expr: non-integer argument

I need the output to appear in decimal form, for example:

./test 
3.5

Best Answer

The date command is pretty flexible about its input. You can use that to your advantage:

#!/bin/bash
var1="23:30"
var2="20:00"

# Convert to epoch time and calculate difference.
difference=$(( $(date -d "$var1" "+%s") - $(date -d "$var2" "+%s") ))

# Divide the difference by 3600 to calculate hours.
echo "scale=2 ; $difference/3600" | bc

Output:

$ ./test.bash
3.50
Related Question