I can't figure out a way (using class definitions) to get months ago. Seconds, days, and minutes are all fine because they're always constants. However since months isn't always constant, i need to know a way for ruby to know how many days are in the current month.
I *think* what he's looking for (by how he says "Months ago") is more like Oracles `months_between` function which will return the numbers of months (as a decimal) between two date values. It takes into account the different lengths of months. http://www.techonthenet.com/oracle/functions/months_between.php
FrustratedWithFormsDesigner
2010-10-04 16:05:27
A:
If you need to know how many days there were in between two dates, say today and the same day number of the last month you can do this:
(Date.today - Date.today.prev_month).to_i
This would give you the number of days in the previous month. If you want to know the number of days for the current month you can instead do:
(Date.today.next_month - Date.today).to_i
Theo
2010-10-04 16:09:45
This is wrong. The first case fails when today is 31st of March, for example. This will return 31, however in February (which is prevuios month to March) can never be more than 29 days.<code><pre>irb(main):013:0> today = Date.parse '2011-03-31'=> #<Date: 2011-03-31 (4911303/2,0,2299161)>irb(main):014:0> (today - today.prev_month).to_i=> 31</pre></code>
DNNX
2010-10-04 16:57:14
Very true, I didn't realize that Date#prev_month would return the last day of the previous month for every day with a number larger than the number of the last day of the previous month (e.g. for March 31, 30, 29 and 28 #prev_month returns Feb 28.
Theo
2010-10-06 07:22:18
+1
A:
If your application uses ActiveSupport (e.g. a Rails application), you can use
3.months.ago
to get the current date less 3 months.
Simone Carletti
2010-10-04 17:29:14