Ruby-on-rails Rails Date 与 Date.today 相比

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2052964/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:07:58  来源:igfitidea点击:

Rails Date compared to Date.today

ruby-on-railsdateconditional-statements

提问by looloobs

I have a birth_date variable in the Date format. I want to compare it to Date.today as shown below. The problem is it is coming back false because it wants to compare the year as well. It is a birthday so I don't care about the year just trying to see if birth_date (month and day) is equal to Date.today.day.month.

我有一个 Date 格式的birth_date 变量。我想将它与 Date.today 进行比较,如下所示。问题是它返回错误,因为它也想比较年份。这是一个生日,所以我不关心年份只是想看看birth_date(月和日)是否等于Date.today.day.month。

Any ideas?

有任何想法吗?

bdays = Soldier.find(:all, :conditions => ["birth_date LIKE ?", Date.today] )

回答by jamuraa

You will need to break up your date, because you want to ignore the year. You will need to use some of the functions given by your SQL provider (the example below uses MySQL):

你需要打破你的约会,因为你想忽略年份。您将需要使用 SQL 提供程序提供的一些功能(以下示例使用 MySQL):

bdays = Soldier.find(:all, :conditions => ["DAY(birth_date) = ? AND MONTH(birth_date) = ?", Date.today.day, Date.today.month])

if you're using SQLite (rails' default database), it will be a bit more complicated because they don't have a real date type:

如果您使用 SQLite(rails 的默认数据库),它会更复杂一些,因为它们没有真正的日期类型:

bdays = Soldier.find(:all, :conditions => ["STRFTIME('%d', birth_date) = ? AND STRFTIME('%m', birth_date) = ?", Date.today.day, Date.today.month])

回答by sbauch

Figured I would add postgres:

想我会添加postgres:

Soldier.where("EXTRACT(DAY FROM birth_date) = ? AND EXTRACT(MONTH FROM birth_date) = ?", Date.today.day, Date.today.month)

Soldier.where("EXTRACT(DAY FROM birth_date) = ? AND EXTRACT(MONTH FROM birth_date) = ?", Date.today.day, Date.today.month)