« September 2007 | Main | November 2007 »

October 2007 Archives

October 10, 2007

Yet Another Reason I Love Linux

Problem: I need to be able to take a date/timestamp strings off of logged error messages and tell whether or not that time was within the last two hours. The strings are all formatted like this:

2007-10-10 09:30:13

The tricky part immediately became what to do when it's 1am and the date string shows 11:30pm on the previous day. What if it's January 1st, 2008 now and the error is from December 31st? This is a tiny project, so I don't feel like writing a function to compare times and take dates/months/years/leap years into account. Luckily, Linux saves the day once again with an awesome built-in function to convert date/time strings into Unix time.

Solution:

# Let's say we've already determined $ERROR_STRING is "2007-10-10 09:30:13"
CUR_TIME=`date +%s`
ERROR_TIME=`date -d "$ERROR_STRING" +%s`
if [ $ERROR_TIME -gt $CUR_TIME ]
then
     echo "ERROR: ERROR_TIME is in the future!"
     exit 1
fi
TIME_DIFF=$(($CUR_TIME - $ERROR_TIME))
if [ $TIME_DIFF -le 7200 ]
then
     echo "ERROR: Error occurred in the last two hours"
     exit 1
else
     echo "OK: Error is more than two hours old
     exit 0
fi

<3 <3 <3 Linux

About October 2007

This page contains all entries posted to NuclearDonkey.net in October 2007. They are listed from oldest to newest.

September 2007 is the previous archive.

November 2007 is the next archive.

Many more can be found on the main index page or by looking through the archives.

Powered by
Movable Type 3.34