开发者

Rails: How I can get yesterday's date?

How can I get yesterday's date?

maybe:

@get_tim开发者_如何学Ce_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 


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 method also provides this options :years, :months, :weeks, :days, :hours, :minutes, :seconds

DateTime advance method

Time advance method


You can just subtract 86400 from a Time object to get one day before. If you are using Rails, or have ActiveSupport included, you can replace 86400 with 1.days.

If you're using a Date object, and not a Time object, just subtract 1 from it.

To check if one date/time is before/after another, just compare the two objects like you would do for numbers:

DateTime.parse("2009-05-17T22:38:42-07:00") < DateTime.parse("2009-05-16T22:38:42-07:00")
# => false
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜