date difference

when i do `date`  i get    Mon Apr 11 16:54:12 EDT 2005

in my shell script i have variable which has date   Sat Apr 9 1:54:12 EDT 2005

how do i find difference i want days hours and minutes
LVL 1
shahrahulbAsked:
Who is Participating?
 
byttaCommented:
To summarize:

#! /bin/bash
refdate="Sat Apr 9 1:54:12 EDT 2005"  #whatever
now=$(date +%s )
ref=$(date +%s -d "$refdate")

diff=$[$now-$ref]
day=$[$diff/60/60]
hour=$[($diff/60/60)%24]
min=$[($diff/60)%60]
sec=$[$diff%60]

echo $day days, $hour hours, $min minutes, $sec seconds
0
 
patthaCommented:
Hi Shahrahub,

date command has got many options:

date '+%option'

show different part of date, where option can be

m,y,d,H,M,S

date '+%d' will give you days,
likewise H will shows hours and S will show seconds and so on.

Regards
Pattha
0
 
ahoffmannCommented:
if you have GNU's version of date there might be a cumbersome solution withing shell (and some helpers like akw, sed, tr). But I'd use perl with Date::Calc instead.

I.g. you better store the dates as seconds since epoch, make calculation much sompler ;-)
0
 
byttaCommented:
Easiest, but not very pretty:
date +%s
gives you time in seconds from epoch to current
date +%s -d "Wed Apr 20 10:42:53 GMT 2005"
gives you time in seconds from epoch to "Wed Apr 20 10:42:53 GMT 2005"

So subtractring one from the other gives you the difference in seconds.

That one's easy to change to days, hours, min
0
 
byttaCommented:
make that:
day=$[$diff/60/60/24]
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.