[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1843
  • Last Modified:

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
0
shahrahulb
Asked:
shahrahulb
  • 3
5 Solutions
 
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:
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
 
byttaCommented:
make that:
day=$[$diff/60/60/24]
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now