Permalink
Browse files

Added year-based time calculations

git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@779 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
  • Loading branch information...
dhh committed Feb 24, 2005
1 parent 32dbf0b commit 5d94fb33c6b862c6b206c55f0d19e3f307fa4056
@@ -54,6 +54,26 @@ def months_since(months)
end
end
+ # Returns a new Time representing the time a number of specified years ago
+ def years_ago(years)
+ change(:year => self.year - years)
+ end
+
+ def years_since(years)
+ change(:year => self.year + years)
+ end
+
+ # Short-hand for months_ago(1)
+ def last_year
+ years_since(1)
+ end
+
+ # Short-hand for months_since(1)
+ def next_year
+ years_since(1)
+ end
+
+
# Short-hand for months_ago(1)
def last_month
months_ago(1)
@@ -87,10 +107,17 @@ def beginning_of_day
# Returns a new Time representing the start of the month (1st of the month, 0:00)
def beginning_of_month
- self - ((self.mday-1).days + self.seconds_since_midnight)
+ #self - ((self.mday-1).days + self.seconds_since_midnight)
+ change(:mday => 1,:hour => 0, :min => 0, :sec => 0, :usec => 0)
end
alias :at_beginning_of_month :beginning_of_month
+ # Returns a new Time representing the start of the year (1st of january, 0:00)
+ def beginning_of_year
+ change(:month => 1,:mday => 1,:hour => 0, :min => 0, :sec => 0, :usec => 0)
+ end
+ alias :at_beginning_of_year :beginning_of_year
+
# Convenience method which returns a new Time representing the time 1 day ago
def yesterday
self.ago(1.day)
@@ -22,6 +22,10 @@ def test_beginning_of_day
def test_beginning_of_month
assert_equal Time.local(2005,2,1,0,0,0), Time.local(2005,2,22,10,10,10).beginning_of_month
end
+
+ def test_beginning_of_year
+ assert_equal Time.local(2005,1,1,0,0,0), Time.local(2005,2,22,10,10,10).beginning_of_year
+ end
def test_months_ago
assert_equal Time.local(2005,5,5,10), Time.local(2005,6,5,10,0,0).months_ago(1)
@@ -38,6 +42,19 @@ def test_months_since
assert_equal Time.local(2006,6,5,10), Time.local(2005,6,5,10,0,0).months_since(12)
assert_equal Time.local(2007,6,5,10), Time.local(2005,6,5,10,0,0).months_since(24)
end
+
+ def test_years_ago
+ assert_equal Time.local(2004,6,5,10), Time.local(2005,6,5,10,0,0).years_ago(1)
+ assert_equal Time.local(1998,6,5,10), Time.local(2005,6,5,10,0,0).years_ago(7)
+ end
+
+ def test_years_since
+ assert_equal Time.local(2006,6,5,10), Time.local(2005,6,5,10,0,0).years_since(1)
+ assert_equal Time.local(2012,6,5,10), Time.local(2005,6,5,10,0,0).years_since(7)
+ # Failure because of size limitations of numeric?
+ # assert_equal Time.local(2182,6,5,10), Time.local(2005,6,5,10,0,0).years_since(177)
+ end
+
def test_ago
assert_equal Time.local(2005,2,22,10,10,9), Time.local(2005,2,22,10,10,10).ago(1)

0 comments on commit 5d94fb3

Please sign in to comment.