subtraction of two dates not working in bash

Viewed 33

I've been overthinking this I am positive however I just need to know the difference between the times.....i.e. how long it took from TimeB to TimeA as it tells me how long something took to run. This is all written in bash.

I have two commands each pulling data to bring in a datetime.

#Reads last date of log input and pulls time out

TimeA = "$(tac /pipeline.log | grep log.inputs.jdbc -m 1 | grep -Eo '[[:digit:]]{4}-[[:digit:]]{2}-[[:digit:]]{2}T[[:digit:]]{2}:[[:digit:]]{2}:[[:digit:]]{2}.[[:digit:]]{2}')"

#reads last timestamp

TimeB = "$(curl -s -XGET -k -u username:password URL/index/_search -H "Content-Type: application/json" -d '{"query":{"query_string":{"query":"ACCOUNT*"}}}' | grep -Eo '@timestamp\"\:\"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{2}' | tail -n1 | grep -Eo '[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{2}')"
TimeA: 2022-09-21T07:20:00,34

TimeB: 2022-09-21T11:40:24.65

Using basic subtractions or anything seems to not present a real value. Any help appreciated.

When I attempt to do basic subtraction ($TimeB - $TimeA). I get

2022-09-21T11:40:24.65-2022-09-21T07:20:00,34

If the dates are different, will just provide an "N/A"

1 Answers
TimeA="2022-09-21T07:20:00,34"
TimeB="2022-09-21T11:40:24.65"

epochA=$(date -d "$TimeA" +"%s")
epochB=$(date -d "$TimeB" +"%s")

((diffInSec=epochA-epochB))
echo $diffInSec

It ignores the floating part of the seconds (on which, btw, you have an inconsistency. One uses a comma, the other a period). If you need it, the simpler is probably to extract them with a cut, and compute diff in 100th of sec

TimeA="2022-09-21T07:20:00,34"
TimeB="2022-09-21T11:40:24.65"

epochA=$(date -d "$TimeA" +"%s")
epochB=$(date -d "$TimeB" +"%s")
fracA=${TimeA##*:???}
fracB=${TimeB##*:???}


((diffIn100thSec=100*epochA+fracA-100*epochB-fracB))
echo $diffIn100thSec

I could have used ${TimeA##*[,.]} to get the fractional part. But I guess, it would be easier that you choose one fractional separator once for all, and then use ${TimeA##*.} or ${TimeA##*,}

Related