How can I get yesterday's date?

How can I get yesterday's date?

may be:

@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)

+63
ruby ruby-on-rails
Jun 27 2018-11-11T00: 00Z
source share
7 answers

Rails

For a date object, you can use:

 Date.yesterday 

Or a time object:

 1.day.ago 

Ruby

Or outside the rails:

 Date.today.prev_day 
+151
Jun 27 2018-11-11T00:
source share

Having tried 1.day.ago and the options 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)> 
+14
Apr 10 '13 at 13:05
source share
 Time.now - (3600 * 24) # or Time.now - 86400 

or

 require 'date' Date.today.prev_day 
+8
Jun 27 '15 at 18:32
source share

Ruby 2.1.2 Original Time

Answer:

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

Evidence:

 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 a second.

86400 = 1 day (60 * 60 * 24)

+6
Jul 01 '14 at 17:43
source share

Use Date.today - 1.days.

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

 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 
+4
Mar 01 2018-12-12T00:
source share

use DateTime.now - 1

 1.9.3p194 :040 > DateTime.now => Mon, 18 Nov 2013 17:58:45 +0530 1.9.3p194 :041 > DateTime.now - 1 => Sun, 17 Nov 2013 17:58:49 +0530 

or DateTime.yesterday

 1.9.3p194 :042 > DateTime.yesterday => Sun, 17 Nov 2013 

or we can use rails advance method for Time and DateTime

 1.9.3p194 :043 > Time.now.advance(days: -1) => 2013-11-17 17:59:36 +0530 1.9.3p194 :044 > DateTime.now.advance(days: -1) => Sun, 17 Nov 2013 17:59:49 +0530 

advance also provides the following parameters :years, :months, :weeks, :days, :hours, :minutes, :seconds

DateTime Date Method

Time advancement method

+4
Nov 18 '13 at 12:39 on
source share

You can simply subtract 86400 from the Time object to get the day before. If you use Rails or have ActiveSupport enabled, you can replace 86400 with 1.days .

If you are using a Date object and not a Time object, simply subtract 1 from it.

To check if there is one date / time before / after another, simply compare the two objects, as you would for numbers:

 DateTime.parse("2009-05-17T22:38:42-07:00") < DateTime.parse("2009-05-16T22:38:42-07:00") # => false 
+3
Jun 27 2018-11-11T00
source share



All Articles