【问题标题】:How can I build a Rails time object representing a certain day in a certain week?如何构建表示某一周中某一天的 Rails 时间对象?
【发布时间】:2012-06-08 18:02:27
【问题描述】:

我也有一个星期数,从像这样的另一个时间对象中提取

other_time.strftime('%W').to_i

%W 给出:

一年中的周数。一周从星期一开始。 (00..53)

我也有一天的名字:

'Tuesday'

如何构建一个 DateTime 对象,该对象代表由周数指示的一周中的星期二?对象的时间分量在此阶段无关紧要,因为它将在后面的步骤中更改。

我正在使用 Rails 3.2.0 和 Ruby 1.9.2p320。

编辑:错误地声明我想要一个 Time 对象。我实际上想要一个 DateTime 对象。

【问题讨论】:

  • “星期二”不是时间。您想要一个日期对象,还是在星期二有您感兴趣的特定时间?
  • 我错了,我想要一个 DateTime 对象。在此阶段为对象设置的实际时间无关紧要,因为它将在稍后的步骤中更改。

标签: ruby-on-rails ruby-on-rails-3 time


【解决方案1】:

您可以对照所需日期检查日期,并进行相应调整。这不是很好,但它确实有效。

$ irb
1.9.3p0 :001 > require 'date'
 => true 
1.9.3p0 :002 > other_date = DateTime.now
 => #<DateTime: 2012-06-08T14:23:44-04:00 ((2456087j,66224s,205565000n),-14400s,2299161j)> 
1.9.3p0 :003 > week = other_date.strftime('%W').to_i
 => 23 
1.9.3p0 :004 > target_day = 2 # Tuesday
 => 2 
1.9.3p0 :005 > while other_date.wday > target_day ; other_date = other_date.prev_day ; end
 => nil 
1.9.3p0 :006 > while other_date.wday < target_day ; other_date = other_date.next_day ; end
 => nil 
1.9.3p0 :007 > other_date # Tuesday of this week
 => #<DateTime: 2012-06-05T14:23:44-04:00 ((2456084j,66224s,205565000n),-14400s,2299161j)> 
1.9.3p0 :008 > other_date.strftime('%W').to_i == week
 => true

【讨论】:

    【解决方案2】:

    我认为你想要的是一个 DateTime 对象。

    http://api.rubyonrails.org/classes/DateTime.html

    【讨论】:

    • 谢谢,我说错了时间对象。不过,仍然想知道如何使用这些标准来构建它。
    【解决方案3】:

    你提到了other_time。我会好好利用它:

    other_time.beginning_of_week + DateTime::DAYNAMES.rotate.index('Tuesday').to_i.days
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-16
      • 1970-01-01
      • 2021-02-17
      相关资源
      最近更新 更多