Created
March 18, 2012 08:24
-
-
Save jsvnm/2069964 to your computer and use it in GitHub Desktop.
monkeypatch to Date to get difference to other date asstring with any or all of years,months,weeks,days. started out as codegolf...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Date | |
# prev_week and next_week, add/remove 7 days * optarg | |
['prev_','next_'].each{|n|define_method(n+'week'){|w=1|send n+'day',7*w}} | |
# other is Date to compare to | |
# wants tells what to include in timediff. default is years,months,weeks,days | |
# by default returns <timediff> from <earlier> to <later> | |
# if abs=true returns <self> is <timediff> later|earlier than <other> | |
def diff_str other, want="ymwd",abs=false | |
return "Both dates are #{self}" if self==other | |
if self<other | |
t,f=self,other | |
a,b=t,f | |
fmt='%s is %s earlier than %s' | |
else | |
t,f=other,self | |
a,b=t,f | |
fmt='%s is %s later than %s' | |
end | |
parts=[] | |
parts<<[0,'year'] if want[?y] | |
parts<<[0,'month'] if want[?m] | |
parts<<[0,'week'] if want[?w] | |
parts<<[0,'day'] if want[?d] | |
parts=parts.map{|c,n| | |
while t<f | |
c+=1 | |
t=t.send"next_#{n}" | |
end | |
c,t=c-1,t.send("prev_#{n}")if t>f | |
[c,n+(c>1??s:'')]*' 'if c>0 }.compact*', ' | |
abs ? parts+" from #{a} to #{b}" | |
: fmt%[self,parts,other] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment