Tuesday, December 21, 2010

The Mysteries of the Unix Date Command.

To do any math on dates is very difficult in any language. But in the Unix/Linux shell this can be a breeze.

This is done by converting all data time in to Seconds.

In Unix this is done by counting seconds from UTC or Universal Constant Time, 1/1/1970

So once you convert in to second, you can do math as usual, then convert time back to date time.


Example of how to convert back and forth

Conversion from Seconds UTC to string
-bash-3.2$ date --date "1970-01-01 1292970890 sec utc"
Tue Dec 21 14:34:50 PST 2010

Conversion from string to Seconds UTC
-bash-3.2$ date --date "12/21/2010 14:34:50 PST" "+%s"
1292970890
-bash-3.2$ date --date "Dec 21 14:34:50 PST 2010" "+%s"
1292970890

Current time
-bash-3.2$ date "+%s"
1292979451

Get Seconds UTC file creation date.
stat -c %Y filename
ls -l
-rw-r--r-- 1 jsokol jsokol       8 Sep 22 18:36 t
 
-bash-3.2$ stat -c %Y t
1285205797


So for doing math on time:


Get file age

(In Bash)
Returns how many hours old
expr \( `date +%s` - `stat -c %Z $filename` \) / 3600

Return age of oldest file in directory
expr \( `date +%s` - `stat -c %Y \`ls -t | tail -1\` ` \) / 3600

Create Shell alias of this
alias oldest='expr \( `date +%s` - `stat -c %Y \`ls -t | tail -1\` ` \) / 3600'

No comments: