Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Make Time#last_month work when invoked on the 31st of a month.

git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@2083 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
  • Loading branch information...
commit 2fed808ee4d572da5d86cb91c704e569589bd7cc 1 parent 70e96c9
Jamis Buck jamis authored
2  activesupport/CHANGELOG
View
@@ -1,5 +1,7 @@
*SVN*
+* Make Time#last_month work when invoked on the 31st of a month.
+
* Add Time.days_in_month, and make Time#next_month work when invoked on the 31st of a month
* Fixed that Time#midnight would have a non-zero usec on some platforms #1836
20 activesupport/lib/active_support/core_ext/time/calculations.rb
View
@@ -9,9 +9,13 @@ def self.append_features(base) #:nodoc:
end
module ClassMethods
+ # Return the number of days in the given month. If a year is given,
+ # February will return the correct number of days for leap years.
+ # Otherwise, this method will always report February as having 28
+ # days.
def days_in_month(month, year=nil)
if month == 2
- (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0)) ? 29 : 28
+ !year.nil? && (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0)) ? 29 : 28
elsif month <= 7
month % 2 == 0 ? 30 : 31
else
@@ -56,17 +60,21 @@ def since(seconds)
# Returns a new Time representing the time a number of specified months ago
def months_ago(months)
- if months >= self.month
- change(:year => self.year - 1, :month => 12).months_ago(months - self.month)
- else
- change(:year => self.year, :month => self.month - months)
- end
+ months_since(-months)
end
def months_since(months)
year, month, mday = self.year, self.month, self.mday
month += months
+
+ # in case months is negative
+ while month < 1
+ month += 12
+ year -= 1
+ end
+
+ # in case months is positive
while month > 12
month -= 12
year += 1
4 activesupport/test/core_ext/time_ext_test.rb
View
@@ -161,4 +161,8 @@ def test_days_in_month
def test_next_month_on_31st
assert_equal Time.local(2005, 9, 30), Time.local(2005, 8, 31).next_month
end
+
+ def test_last_month_on_31st
+ assert_equal Time.local(2004, 2, 29), Time.local(2004, 3, 31).last_month
+ end
end
Please sign in to comment.
Something went wrong with that request. Please try again.