Rails: How I can get yesterday's date?

How can I get yesterday's date?

maybe:

@get_time_now    = Time.now.strftime('%m/%d/%Y') / 86400 

or

@get_time_now    = Time.now.strftime('%m/%d/%Y') - 1.day

or

@get_time_now    = Time.now. / 86400 

86400 = 1 day, right? (60 * 60 * 24)


Rails

For a date object you could use:

Date.yesterday

Or a time object:

1.day.ago

Ruby

Or outside of rails:

require 'date'

Date.today.prev_day

After trying 1.day.ago and variants on it:

irb(main):005:0> 1.day.ago
NoMethodError: undefined method `day' for 1:Fixnum

if found that Date.today.prev_day works for me:

irb(main):016:0> Date.today.prev_day
=> #<Date: 2013-04-09 ((2456392j,0s,0n),+0s,2299161j)>

Time.now - (3600 * 24)   # or Time.now - 86400

or

require 'date'

Date.today.prev_day

Ruby 2.1.2 Native Time

Answer:

Time.at(Time.now.to_i - 86400)

Proof:

2.1.2 :016 > Time.now
 => 2014-07-01 13:36:24 -0400 
2.1.2 :017 > Time.now.to_i
 => 1404236192 
2.1.2 :018 > Time.now.to_i - 86400
 => 1404149804 
2.1.2 :019 > Time.at(Time.now.to_i - 86400)
 => 2014-06-30 13:36:53 -0400 

One Day of Seconds.

86400 = 1 day (60 * 60 * 24)


Use Date.today - 1.days.

Date.yesterday depends on the current time and your offset from GMT

1.9.3-p125 :100 > Date.today
 => Wed, 29 Feb 2012 
1.9.3-p125 :101 > Date.yesterday
 => Wed, 29 Feb 2012 
1.9.3-p125 :102 > Date.today - 1.days
 => Tue, 28 Feb 2012