good date lib?

36 views
Skip to first unread message

Colin Thomas-Arnold

unread,
Sep 14, 2012, 3:33:15 PM9/14/12
to rubym...@googlegroups.com
i have wasted an entire morning writing code that allows this:


(main)> feb_28_2012 = 1330473600  # what, you don't have this memorized?
=> 1330473600
(main)> Time.at(feb_28_2012)
=> 2012-02-28 17:00:00 -0700
(main)> Time.at(feb_28_2012).delta(days:1)
=> 2012-02-29 17:00:00 -0700
(main)> Time.at(feb_28_2012).delta(days:2)
=> 2012-03-01 17:00:00 -0700
(main)> Time.at(feb_28_2012).delta(months:1)
=> 2012-03-28 17:00:00 -0600  # look, the time didn't change, event though there was a DST change!
(main)> Time.at(feb_28_2012).delta(years:1)
=> 2013-02-28 17:00:00 -0700
(main)> Time.at(feb_28_2012).delta(days:1, years:1)
=> 2013-02-28 17:00:00 -0700
(main)> Time.at(feb_28_2012).delta(days:1, years:1, months:1)
=> 2013-03-29 17:00:00 -0600

(main)> Time.at(feb_28_2012).delta(days:1, months:11)
=> 2013-01-29 17:00:00 -0700

# what is 1/29/2013 plus two months?  easy!  march 29, 2013
(main)> Time.at(feb_28_2012).delta(days:1, months:13)
=> 2013-03-29 17:00:00 -0600

# yeah, smart guy? well then what is 1/29/2013 plus ONE month.
# it's feb 28th.  trust me.  when someone says "see you in a month!"
# they mean "next month", not "in the early part of two months in the future",
# which is where the math will take you if you don't add a "day of month" correction.
(main)> Time.at(feb_28_2012).delta(days:1, months:12)
=> 2013-02-28 17:00:00 -0700

# unfortunately you will end up with stuff like this:
(main)> Time.at(feb_28_2012) == Time.at(feb_28_2012).delta(days:1, months:12).delta(months:-12)
=> true


Did I just reinvent a wheel, or is this nifty and everyone needs it?


and if the latter => put it in sugarcube, or a separate gem?  I don't want sugarcube to get "FAT", but this is just one method that does this insanity (i hate dates).



Clay Allsopp

unread,
Sep 15, 2012, 2:19:37 PM9/15/12
to rubym...@googlegroups.com
Ah, that is nifty/necessary.

Ideally, the time additions of ActiveSupport would be added to https://github.com/hookercookerman/motion_support, so the Rails `1.day + 1.year` could be used.
Reply all
Reply to author
Forward
0 new messages