John
John

Reputation: 634

Rails times comparison

I need to compare two dates: One date is taken form a table, created_at column and the other one is taken from (i don't know, server time, or client time).

So is it ok to compare them like this?

t.strftime("%Y-%d-%m") == Time.now.strftime("%Y-%d-%m")

Where t is the table row.create_at.

And now about, the time that my t will be compared with, from where is Time.now taken from my computer, or from the server?

If is taken from my computer, how can I use the server time?

Upvotes: 1

Views: 225

Answers (2)

Gopal S Rathore
Gopal S Rathore

Reputation: 9995

Since Rails know that your time information is stored as UTC in the database it will convert any time you give it to UTC.

I think we should use

t.strftime("%Y-%d-%m") == Time.zone.now.strftime("%Y-%d-%m")

at the place of

t.strftime("%Y-%d-%m") == Time.now.strftime("%Y-%d-%m")

Just be sure to never construct the query string by hand and always use Time.zone.now as the base and you should be safe.

For more info, go through working with time zones

Upvotes: 3

Tumas
Tumas

Reputation: 1727

This comparison will work as expected because you are converting time to string and then comparing strings. I usually convert to integer for comparison but since you are comparing dates you would need to convert time objects to date object first.

Ruby is executed on the server so Time.now is always server time. If you want to compare with utc time use Time.current

Upvotes: 2

Related Questions