Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare Date-Time Stamps [duplicate]

Tags:

shell

unix

I am looking to write a shell script that will compare the time between two date-time stamps in the format:

2013-12-10 13:25:30.123
2013-12-10 13:25:31.123

I can split the date and time if required (as the comparison should never be more than one second - I am looking at a reporting rate), so I can format the time as 13:25:30.123 / 13:25:31.123.

like image 741
Dustin Cook Avatar asked Dec 11 '25 09:12

Dustin Cook


1 Answers

To just find the newer (or older) of the two timestamps, you could just use a string comparison operator:

time1="2013-12-10 13:25:30.123"
time2="2013-12-10 13:25:31.123"

if [ "$time1" > "$time2" ]; then
    echo "the 2nd timestamp is newer"
else
    echo "the 1st timestamp is newer"
fi

And, to find the time difference (tested):

ns1=$(date --date "$time1" +%s%N)
ns2=$(date --date "$time2" +%s%N)
echo "the difference in seconds is:" `bc <<< "scale=3; ($ns2 - $ns1) / 1000000000"` "seconds"

Which, in your case prints

the difference in seconds is: 1.000 seconds
like image 75
MarcoS Avatar answered Dec 13 '25 22:12

MarcoS