Duong Tuan Nhat
Duong Tuan Nhat

Reputation: 39

Compare date on a datetime column in rails active record

I have a problem when trying to compare a datetime column equal to a date in rails when using mysql. For example, I want to find user create in 2020-05-01 but type of "created_at" column is datetime, firstly I try:

User.where("date(created_at) = ?", date) # date is 2020-05-01

But when I use rails in japanese timezone and an user created at 2020-05-01 07:00 GMT+9, rails will save it in mysql with GMT+0 . It mean created_at is 2020-04-30 22:00 GMT+0 in mysql. And then User.where("date(created_at) = ?", date) will not return this one.

Is there a good solution for this case?

Upvotes: 0

Views: 1825

Answers (1)

Yshmarov
Yshmarov

Reputation: 3729

Something like this

# convert date to datetime
date = "2020-05-01".to_datetime 

So you can do:

User.where(created_at: date.beginning_of_day..date.end_of_day)

With the comment below, it becomes even shorter:

User.where(created_at: created_at: date.all_day)

date.all_day will give you something like

Sun, 17 May 2020 00:00:00 UTC +00:00..Sun, 17 May 2020 23:59:59 UTC +00:00

Upvotes: 5

Related Questions