How to Find Time Difference in Unix Script
If you need to find the difference between two times, whether they differ by only a few seconds or by years, you can do this in the GNU version of Unix with the "date" command. However, the procedure is not intuitive, as the date command doesn't directly provide a flag or argument for this procedure. In addition, multiple versions of the date command exist in Unix. Note that what works in the GNU version of the date command will not work with the BSD version.
-
Unix Epoch
-
The key to solving this problem is understanding how the computer actually keeps track of time. A Unix computer stores all times as the number of seconds that have elapsed since the Unix Epoch. The Unix Epoch is midnight of January 1, 1970.
Getting the Seconds Since the Unix Epoch
-
You can get the number of seconds since the Unix Epoch to a given date using a combination of the "+%s" flag and the "--date" command. Type the following into a shell to get the number of seconds from the Unix Epoch to March 11, 2011:
date --date 2011-03-11 +%s
The result will be: 1299823200. You can use any date-time format that you can parse by the "date" command in this script. You can type "man date" into your shell to read about all the valid date formats.
-
The Solution
-
As you can take any given date or time in a Unix compatible format and convert it to the seconds before or since the Unix Epoch, you can find the difference between any two times by subtracting the results of two of these commands.
Type the following commands into your shell:
d1=`date --date 2011-03-11 +%s`
d2=`date --date 2010-05-12 +%s`
echo "$(((d1-d2))) seconds difference"
In the first two lines, the ` character is not a quote mark. It is a back-tick. You can locate this character to the left of the "1" key on a standard U.S. keyboard.
The output should be the difference between the two times in seconds. If you need, you can convert this into minutes, hours, days, and so on by dividing by the number of seconds in a minute, minutes in an hour or hours in a day.
A Script
-
As it would be a nuisance to type out those three long commands every time, you should encapsulate it into a script. Open your favorite text editor and paste the following:
#!/usr/bin/env bash
d1=`date --date $1 +%s`
d2=`date --date $2 +%s`
echo "$(((d1-d2))) seconds difference"
This changes a few things. The top line lets the current shell know that you write this script to use the language of the "bash" shell. As you replace the dates in the two date commands with "$1" and "$2," you can pass new dates to the script each time you run it. Once again, in the first two lines, you use the back-tick `, not a single quote.
Save your script with the name "timediff.sh" and run the command "chmod +x timediff.sh" in your shell to let Unix know that it has permission to run this as a script.
After you do this, you can find the difference between any two dates and times by typing:
./timediff.sh 2010-9-13 1981-1-14
-