diff options
Diffstat (limited to 'lib')
-rw-r--r-- | lib/ayk/age.rb | 70 |
1 files changed, 53 insertions, 17 deletions
diff --git a/lib/ayk/age.rb b/lib/ayk/age.rb index 0ecc40e..f51b8f1 100644 --- a/lib/ayk/age.rb +++ b/lib/ayk/age.rb @@ -1,37 +1,73 @@ #! /usr/bin/env ruby # -*- coding: UTF-8 -*- - -#---------------------------------------------------------------------------- # -# File : age.rb -# Author : Jérémy Zurcher <jeremy@asynk.ch> -# Date : 22/08/09 +# Copyright (c) 2009-2011 Jérémy Zurcher +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # #---------------------------------------------------------------------------- - +# require 'date' - +# class DateTime # returns an array representing years,months,days,hours,minutes,seconds # between self and futur DateTime at def age at=DateTime.now return [nil]*6 if at<self - # years + return [0]*6 if at==self years = at.year-self.year + months = at.month-self.month + # move years forward x = self>>(12*years) if x>at - years -= 1 - x<<=12 - end - months = at.month-x.month+(11*(at.year-x.year)) - x >>=months - if x>at - months -= 1 - x <<=1 + # move months backward + x>>=months + # adjust years and months + years-=1 + months+=12 + else + # move months forward + x>>=months end - # 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 |