IRH301010
IRH301010

Reputation: 71

Get yesterday's date

This may be an obvious question but im new to ruby and I've spent ages trying to get yesterdays date for a cucumber test that checks a url that includes yesterday's date. for example: http://www.blah.co.uk/blah/blah/schedule/2011-11-28

I've created the following within my helper methods:

def Helper.get_date
  Time.now.strftime('%Y-%m-%d') / 1.day
end

But it doesn’t like the /1.day or – 1.day or – 86400 (seconds).

Upvotes: 3

Views: 4255

Answers (6)

kwarrick
kwarrick

Reputation: 6190

As an addition to the answers here, I think its worth while to point out the quintessential Ruby on Rails helper methods for Integers and Numerics:

ruby-1.8.7-p352 :002 > 1.days.ago
=> Tue, 29 Nov 2011 04:55:21 UTC +00:00 

ruby-1.8.7-p352 :003 > 1.month.ago
=> Sun, 30 Oct 2011 04:55:54 UTC +00:00 

ruby-1.8.7-p352 :004 > 1.week.from_now
=> Wed, 07 Dec 2011 04:56:17 UTC +00:00 

Upvotes: 2

BM5k
BM5k

Reputation: 1230

Date.yesterday should work:

$ bundle exec rails console
Loading development environment (Rails 3.0.7)
ree-1.8.7-2011.03 :001 > Date.yesterday.to_s
 => "2011-11-29"
ree-1.8.7-2011.03 :002 > "#{ Date.yesterday }"
 => "2011-11-29"

Upvotes: 1

Nikita Barsukov
Nikita Barsukov

Reputation: 2984

I'd use something like

def Helper.get_date
  (Time.now - 60*60*24).strftime('%Y-%m-%d')
end

This is a good reference to arguments that strftime can take: http://www.ruby-doc.org/core-1.9.3/Time.html#method-i-strftime

Upvotes: 0

steenslag
steenslag

Reputation: 80065

(Date.today-1).strftime('%Y-%m-%d')

Would be a non rails-specific way.

Upvotes: 7

Jon M
Jon M

Reputation: 11705

You can use some of the methods in ActiveSupport (which will be included if you're in a Rails app) to do the following:

DateTime.yesterday.strftime('%Y-%m-%d')

EDIT: As it's a standard date format, you could also reference the standard directly:

DateTime.yesterday.iso8601

Upvotes: 9

Hauleth
Hauleth

Reputation: 23556

Use:

def Helper.get_date
  (Time.now / 1.day).strftime('%Y-%m-%d')
end

Because you are decrease date not a string.

Upvotes: 1

Related Questions