Skip to content
This repository
Browse code

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 authored August 31, 2005
2  activesupport/CHANGELOG
... ...
@@ -1,5 +1,7 @@
1 1
 *SVN*
2 2
 
  3
+* Make Time#last_month work when invoked on the 31st of a month.
  4
+
3 5
 * Add Time.days_in_month, and make Time#next_month work when invoked on the 31st of a month
4 6
 
5 7
 * Fixed that Time#midnight would have a non-zero usec on some platforms #1836
20  activesupport/lib/active_support/core_ext/time/calculations.rb
@@ -9,9 +9,13 @@ def self.append_features(base) #:nodoc:
9 9
         end
10 10
 
11 11
         module ClassMethods
  12
+          # Return the number of days in the given month. If a year is given,
  13
+          # February will return the correct number of days for leap years.
  14
+          # Otherwise, this method will always report February as having 28
  15
+          # days.
12 16
           def days_in_month(month, year=nil)
13 17
             if month == 2
14  
-              (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0)) ?  29 : 28
  18
+              !year.nil? && (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0)) ?  29 : 28
15 19
             elsif month <= 7
16 20
               month % 2 == 0 ? 30 : 31
17 21
             else
@@ -56,17 +60,21 @@ def since(seconds)
56 60
 
57 61
         # Returns a new Time representing the time a number of specified months ago
58 62
         def months_ago(months)
59  
-          if months >= self.month 
60  
-            change(:year => self.year - 1, :month => 12).months_ago(months - self.month)
61  
-          else
62  
-            change(:year => self.year, :month => self.month - months)
63  
-          end
  63
+          months_since(-months)
64 64
         end
65 65
 
66 66
         def months_since(months)
67 67
           year, month, mday = self.year, self.month, self.mday
68 68
 
69 69
           month += months
  70
+
  71
+          # in case months is negative
  72
+          while month < 1
  73
+            month += 12
  74
+            year -= 1
  75
+          end
  76
+
  77
+          # in case months is positive
70 78
           while month > 12
71 79
             month -= 12
72 80
             year += 1
4  activesupport/test/core_ext/time_ext_test.rb
@@ -161,4 +161,8 @@ def test_days_in_month
161 161
   def test_next_month_on_31st
162 162
     assert_equal Time.local(2005, 9, 30), Time.local(2005, 8, 31).next_month
163 163
   end
  164
+
  165
+  def test_last_month_on_31st
  166
+    assert_equal Time.local(2004, 2, 29), Time.local(2004, 3, 31).last_month
  167
+  end
164 168
 end

0 notes on commit 2fed808

Please sign in to comment.
Something went wrong with that request. Please try again.