简体   繁体   中英

How to parse through a date field using SQL

I'm using Ruby on Rails, and I have a Users table which has a birthday field that is type date.

What I want to do is be able to show an alert if it is a particular Users birthday. The problem I realized i'm having is that in all my test cases I would make someones birthday today to see if it worked, however if I make someones birthday today but 10 years ago, my alert system stops working because the years do not match.

So basically, I want to get the users birthday, but only the day and month and check to see if it matches todays day and month. Is there some sort of raw query I should be using, or should I be thinking of something else?

You can use:

select t.*
from t
where month(t.dob) = month(curdate()) and day(t.dob) = day(curdate());

Note: most databases support month() and day() . All have this functionality but the exact functions might depend on the database.

您可以参考此https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html来获取datetime的日期和月份部分

It's possible to do this in a Rails-y fashion by passing your DB's method of extracting month and day into User.where .

For instance, to get users born on Feb 14 in SQLite3:

User.where("strftime('%m %d', birthday) = ?", "02 14")

in MySQL:

User.where("month(birthday) = ? AND day(birthday) = ?", "02", "14")`

in Postgres:

User.where("date_part('month', birthday) = ? AND date_part('day', birthday) = ?", "02", "14")

The above snippets assume the column on your users table is named birthday .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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