Velvet Star Monitor

Standout celebrity highlights with iconic style.

news

How to subtract two time stamps along with their dates in bash?

Writer Emily Wong

I have a two variables :

A= 04.07.2019 23:29:40
B= 05.07.2019 01:15:52

I want to perform a arithmetic operation C = A - B using bash.

Can some one help me in converting them into integers. In general the dates are different every time, that is why cant neglect the dates.

Output should be in seconds/minutes. If possible in HH:MM:SS format.

3

1 Answer

You can use date to convert to timestamp which is seconds, subtract the seconds and then convert back to HH:MM:SS.

Unfortunately, date doesn't read the specified format, so we need to turn around the DD.MM.YYYY to YYYY-MM-DD.

{
A="04.07.2019 23:29:40"
B="05.07.2019 01:15:52"
# Create a function to change DD.MM.YYYY HH:MM:SS to YYYY-MM-DD HH:MM:SS.
convert_date(){ printf '%s-%s-%s %s' ${1:6:4} ${1:3:2} ${1:0:2} ${1:11:8}; }
# Convert to timestamp
A_TS=$(date -d "$(convert_date "$A")" +%s)
B_TS=$(date -d "$(convert_date "$B")" +%s)
# Subtract
DIFF=$((B_TS-A_TS))
# convert to HH:MM:SS (note, that if it's more than one day, it will be wrong!)
TZ=UTC date -d @$DIFF +%H:%M:%S
}

Output:

01:46:12

Using a more general function to subtract the dates:

diff_dates(){ TS1=$(date -d "$1" +%s) TS2=$(date -d "$2" +%s) [ $TS2 -ge $TS1 ] \ && TZ=UTC date -d @$((TS2-TS1)) +%H:%M:%S \ || TZ=UTC date -d @$((TS1-TS2)) +-%H:%M:%S
}
convert_date(){ printf '%s-%s-%s %s' ${1:6:4} ${1:3:2} ${1:0:2} ${1:11:8};
}

Usage:

$ A="04.07.2019 23:29:40"
$ B="05.07.2019 01:15:52"
$ diff_dates "$(convert_date "$A")" "$(convert_date "$B")"
01:46:12

or if you already have date-compatible dates:

$ diff_dates "2019-07-04 23:29:40" "2019-07-05 01:15:52"
01:46:12
$ diff_dates "2019-07-05 01:15:52" "2019-07-04 23:29:40"
-01:46:12
9

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy