Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Date Subtraction (e.g. 90 days Ago)

Tags:

date

ruby

I've been a bit spoiled by the joda-time API of:

DateTime now = new DateTime(); DateTime ninetyDaysAgo = now.minusDays(90); 

I'm trying to do a similar thing in Ruby, but I'm

now = Time.now ninetyDaysAgo = now - (90*24) 

However, the math is off here (I'm really working with dates at midnight).

Is there friendly API for date subtraction?

like image 799
darthtrevino Avatar asked Mar 02 '11 17:03

darthtrevino


People also ask

How do I get the last date of the month in Ruby?

Yes you can use Date. new(year, month, -1).

How do I get the current date in Ruby?

Ruby | DateTime now() function DateTime#now() : now() is a DateTime class method which returns a DateTime object denoting the given calendar date. Return: DateTime object denoting the given calendar date.


2 Answers

require 'date' now = Date.today ninety_days_ago = (now - 90) 

Running this thru the IRB console I get:

>>require 'date' now = Date.today ninety_days_ago = (now - 90)  require 'date' => false now = Date.today => #<Date: 2011-03-02 (4911245/2,0,2299161)> ninety_days_ago = (now - 90) => #<Date: 2010-12-02 (4911065/2,0,2299161)> 

If you need the time you could just say now = DateTime.now

like image 54
Matt Avatar answered Oct 13 '22 09:10

Matt


For those using Rails, check out the following:

DateTime.now - 10.days => Sat, 04 May 2013 12:12:07 +0300  20.days.ago - 10.days => Sun, 14 Apr 2013 09:12:13 UTC +00:00 
like image 45
Abdo Avatar answered Oct 13 '22 07:10

Abdo