Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I have a command that outputs a single date in whatever format I please. Now I need a simple way of calculating (with bash) how many hours have passed since that date (default is yyyy-mm-dd hh:mm).

The only way I can think of doing this is by using several ifs, but I was hoping there might be a quick one-line method. Perhaps using the date command?

Just an example for clarity:
Right now it is 2011-05-23 12:16.
The first command outputs 2011-05-22 08:34.
I need a command (or a few piped commands) that output 27, as in: "27 hours (rounded down) have passed since the specified date".

Is there a quick'n simple way to achieve that? Or am I bound to use conditionals (not that it'd be overly complex).

share|improve this question
    
unix.com/tips-tutorials/… this is a small script regarding subtracting dates. –  Rinzwind May 23 '11 at 14:48

1 Answer 1

up vote 2 down vote accepted

Generally speaking for times in Unix it's simplest to convert both datetimes into Unix Timestamps (that are seconds since 1970-1-1 00:00), subtract one from other and, in your case, divide by 3600 to get the hours.

SECONDS=`expr $(date -d "20110523" +%s) - $(date -d "20110522" +%s)`
expr $SECONDS / 3600

#Return is 24
share|improve this answer
    
Perfect! Didn't know about Unix Timestamps. –  Malabarba May 23 '11 at 15:00
    
That's right for about a second. SECONDS is a special bash variable that changes every second. Also, bash can do integer math; no need for expr. –  geirha May 26 '11 at 23:16

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.