简体   繁体   English

Rails日期与Date.today相比

[英]Rails Date compared to Date.today

I have a birth_date variable in the Date format. 我在Date格式中有一个birth_date变量。 I want to compare it to Date.today as shown below. 我想将它与Date.today进行比较,如下所示。 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. 这是一个生日,所以我不关心今年只是想看看birth_date(月和日)是否等于Date.today.day.month。

Any ideas? 有任何想法吗?

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

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])

想我会添加postgres:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM