1

I have 2 strings s1 and s2 (representing dates) in bash of the form

s1="Fri Sep 10 22:24:51 IST 2021"
s2="Fri Sep 10 22:45:55 IST 2021"

I want to subtract these dates and get the result in the format HH:MM:SS

I have tried the following piece of code (to at least convert the strings to date)

d1=$(date -s $s1 +%s)
d2=$(date -s $s2 +%s)
d3=$d2-$d1
echo "$d3"

but ended up with the following error

date: extra operand ‘10’

This is the sample output I desire

Subtracted Date in HH:MM:SS is "00:21:04"

I am stuck here and don't know how to proceed further. Any help on this would be appreciated!

Ujjwal
  • 23
  • 4
  • This might help: [How to subtract two time stamps along with their dates in bash?](https://askubuntu.com/q/1158870/336375) – Cyrus Sep 10 '21 at 19:13
  • 2
    You need to quote the parameter expansions, and use arithmetic expansion to do the actual arithmetic. – chepner Sep 10 '21 at 19:17
  • @Cyrus [How to subtract two time stamps along with their dates in bash?](https://askubuntu.com/q/1158870/336375) is not able to track the difference exceeding 24 hours. Any idea on how to proceed in that case? – Ujjwal Sep 10 '21 at 19:37

1 Answers1

2

Convert both timestamps with GNU date to seconds since 1970-01-01 00:00:00 UTC. Subtract them and convert the result to the desired format.

s1="Fri Sep 10 22:24:51 IST 2021"
s2="Fri Sep 10 22:45:55 IST 2021"

diff=$(( $(date -d "$s2" +%s) - $(date -d "$s1" +%s) ))
date -d "@$diff" -u +%H:%M:%S

Output:

00:21:04
Cyrus
  • 84,225
  • 14
  • 89
  • 153
  • This doesn't work if the difference between both dates is greater than 24 hours. This is correct for the provided specific dates but is not a general method – Ujjwal Sep 11 '21 at 06:08
  • For a general method you would have to remove the last line and calculate the hours, minutes and seconds from $diff. – Cyrus Sep 11 '21 at 16:57