我如何从红宝石中获得当前的工作日?

时间:2011-07-28 12:23:21

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

例如今天是28/07/2011 我如何在星期一的第一天获得星期五,即2011年7月25日在红宝石

2 个答案:

答案 0 :(得分:32)

>> Date.today.beginning_of_week.strftime('%d/%m/%Y')
#=> 25/07/2011

有关详细信息,请参阅Rails下的TimeDate类;有关格式化选项的信息,请参阅strftime

答案 1 :(得分:26)

没有Rails / ActiveSupport:

phrogz$ irb
> require 'date'
> now = Date.today
#=> #<Date: 2011-07-28 (4911541/2,0,2299161)>
> sunday = now - now.wday
#=> #<Date: 2011-07-24 (4911533/2,0,2299161)>
> monday = now - (now.wday - 1) % 7
#=> #<Date: 2011-07-25 (4911535/2,0,2299161)>
> monday.iso8601
#=> "2011-07-25"
> monday.strftime('%d/%m/%Y')
#=> "25/07/2011"

有关详情,请参阅标准库中的Date课程。

作为一种方法包装:

require 'date'
# For weekdays to start on Monday use 1 for the offset; for Tuesday use 2, etc.
def week_start( date, offset_from_sunday=0 )
  date - (date.wday - offset_from_sunday)%7
end

sun = Date.parse '2011-07-24'
week_start(sun,0).strftime('%a, %b-%d')  #=> "Sun, Jul-24"
week_start(sun,1).strftime('%a, %b-%d')  #=> "Mon, Jul-18"