January 12, 2015
January 12, 2015 – 10:23 pmI had been looking for a way to do some “date math” in linux. Normally I use perl and the date manipulation modules, but this time I needed something that would work in linux without the extras. Note that this won’t work in Solaris or AIX unless they have the updated GNU date stuff installed – but at least on Linux this works. As an example here, I’m looking to calculate the difference in hours, minutes and seconds between two dates that are relatively close to each other. In my case, they’ll never be more than 24 hours apart, so this is straightforward. The trick is that to do anything beyond a simple “day” based date, it requires converting back to epoch form. If you simply want the difference between two calendar days, its alot simpler than this.
- Start with date 1, and convert to count of seconds in epoch form :
$ date -d “2014-01-13T04:30:30” +%s1389562230
- Now get the second date and convert it to count of seconds in epoch form :
$ date -d “2014-01-12T21:15:15” +%s1389536115
- Since we now have two epoch times, we can perform a difference between them using good old basic math with “expr” :
$ expr 1389562230 – 138953611526115
- We now have a count of seconds between the dates, so lets convert that count of seconds to something usable like hours, minutes, and seconds :
$ date -u -d @26115 +”%T”07:15:15
So now that we have the approach, this can all be summed up into a basic one liner :
$ date -u -d @$(expr `date -d “2014-01-13T04:30:30” +%s` – `date -d “2014-01-12T21:15:15” +%s`) +”%T”07:15:15
The key is just remembering to feed the date in with the form that includes the magic “T” in the middle, which allows the addition of the time. Hard a hard time finding that one. So feed the dates in with the form of :
“YYYY-MM-DD”+”T”+”HH:MM:SS”
And all works out pretty well, and no need for any special perl modules. All done inside a bash script.
Sorry, comments for this entry are closed at this time.