如何获得昨天的日期?
也许:
@get_time_now = Time.now.strftime('%m/%d/%Y') / 86400
要么
@get_time_now = Time.now.strftime('%m/%d/%Y') - 1.day
要么
@get_time_now = Time.now. / 86400
86400 = 1天,对吗?(60 * 60 * 24)
Answers:
对于日期对象,可以使用:
Date.yesterday
或时间对象:
1.day.ago
或在铁轨外:
Date.today.prev_day
经过尝试1.day.ago
和变体之后:
irb(main):005:0> 1.day.ago
NoMethodError: undefined method `day' for 1:Fixnum
如果发现Date.today.prev_day
对我有用:
irb(main):016:0> Date.today.prev_day
=> #<Date: 2013-04-09 ((2456392j,0s,0n),+0s,2299161j)>
Date.today - 1
Ruby 2.1.2本地时间
回答:
Time.at(Time.now.to_i - 86400)
证明:
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
一日。
86400 = 1天(60 * 60 * 24)
使用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
或DateTime.yesterday
1.9.3p194 :042 > DateTime.yesterday
=> Sun, 17 Nov 2013
或者我们可以使用rails
advance
方法Time
和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
方法还提供了此选项 :years, :months, :weeks, :days, :hours, :minutes, :seconds