summaryrefslogtreecommitdiffstats
path: root/lib
diff options
context:
space:
mode:
Diffstat (limited to 'lib')
-rw-r--r--lib/ayk/age.rb46
1 files changed, 13 insertions, 33 deletions
diff --git a/lib/ayk/age.rb b/lib/ayk/age.rb
index f51b8f1..05a7407 100644
--- a/lib/ayk/age.rb
+++ b/lib/ayk/age.rb
@@ -32,45 +32,25 @@ class DateTime
def age at=DateTime.now
return [nil]*6 if at<self
return [0]*6 if at==self
+ # hours, minutes, seconds
+ hms = (at.hour*3600+at.minute*60+at.sec)-(self.hour*3600+self.minute*60+self.second)
+ hours,r = (hms<0 ? (hms+24*3600) : hms ).divmod 3600
+ mins,secs = r.divmod 60
+ # years, months, days
years = at.year-self.year
months = at.month-self.month
- # move years forward
- x = self>>(12*years)
- if x>at
- # move months backward
- x>>=months
- # adjust years and months
+ days = at.mday-self.mday
+ # adjust years and months
+ days-=1 if hms<0
+ months-=1 if days<0
+ if months<0
years-=1
months+=12
- else
- # move months forward
- x>>=months
end
+ # move years months forward
+ x = self>>(12*years+months)
+ # compute days
days = (at-x).to_i
- if days<0
- # move 1 month backward
- x<<=1
- # adjust months and days
- months-=1
- days = (at-x).to_i
- end
- # move days forward
- x += days
- if x>at
- # move 1 day backward
- x-=1
- days-=1
- if days<0
- x+=1
- x<<=1
- months-=1
- days = (at-x).to_i
- x+=days
- end
- end
- # hours
- hours,r = (at.to_time-x.to_time).to_i.divmod 3600
- mins,secs = r.divmod 60
# return
[years,months,days,hours,mins,secs]
end