Rails上一个星期日与任何DateTime关系 [英] Rails Previous Sunday in Relation to Any DateTime

查看:99
本文介绍了Rails上一个星期日与任何DateTime关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Rails 3应用程序。给定一个DateTime,我需要生成前一个星期天的日期时间。如果DateTime是星期天,那我想要那个星期天呢。以下是一些例子:

Working with a Rails 3 application. Given a DateTime, I need to produce the Datetime for the previous Sunday. If the DateTime is a Sunday, then I want that Sunday itself back. Here's some examples:


November 7, 2011 => November 6, 2011
November 6, 2011 => November 6, 2011
November 5, 2011 => October 30, 2011

任何想法?我有点卡住了

Any ideas? I'm a bit stuck.

推荐答案

class DateTime
  def previous_sunday
    self - wday
  end
end

...但是这样容易,没有理由将猴子修补到课程中:)

…but this is so easy, there's no reason to monkey patch it into the class :)

irb(main):001:0> require 'date'; now = DateTime.now
#=> #<DateTime: 2011-11-10T21:10:04-07:00 (…)>
irb(main):002:0> sunday = now - now.wday
#=> #<DateTime: 2011-11-06T21:10:04-07:00 (…)>

wday (工作日)将 0 任何星期日,所以不会更改日期。

The wday (weekday) will be 0 for any Sunday, and so no change to the date will take place.

这篇关于Rails上一个星期日与任何DateTime关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆