Reputation: 7950
I'm using MongoDB and Mongoid in my project. I have some difficulties with ordering "Time" field data.
As you know, eventhough you set a field type as Time
inside your Mongoid Document, time data is stored as this format (note that I use +2 hours offset to get my own timezone's time instead of UTC):
Mon, 31 Dec 2012 08:30:00 EET +02:00
I'm not sure if I'm missing something but this is what happens to me.
I want to use that Time
data inside one of my views. I need to sort some related stuff by ONLY Hour:Minute
format. I don't want Rails to take care of the DATE part of the field data. Because whenever a new Time
record inserted to DB, it takes the day info as CURRENT DAY.
Because of it saves CURRENT DAY for each of new Time
records, when I try to order_by("hour DESC")
NEW records always retrieved first eventhough HOUR part of the data is bigger!
First data:
=> Tue, 27 Nov 2012 19:50:00 EET +02:00
Second data:
=> Mon, 24 Dec 2012 18:45:00 EET +02:00
As you know, normally, 19:50 is bigger than 18:45. But in this scenario, because of Rails takes day
info into calculation, 18:45 looks like bigger than 19:50!
So what is the work around for this issue?
Thanks in advence.
Upvotes: 1
Views: 1196
Reputation: 990
Best way to store time of day is as seconds_since_midnight in an Integer field. Then you can just sort normally.
field :time, type: Integer
validates :time, presence: true, numericality: { greater_than_or_equal_to: 0, less_than_or_equal_to: 86399 }
http://api.rubyonrails.org/classes/DateTime.html#method-i-seconds_since_midnight http://api.rubyonrails.org/classes/Time.html#method-i-seconds_since_midnight
Upvotes: 1
Reputation: 7950
I've found an answer to this at Mongoid's issues list: https://github.com/mongoid/mongoid/issues/1169
That's really weired...
If I understood well, Time
field type is totally useless! What is the difference between DateTime
and Time
then??
You even can not compare hours and minutes ONLY inside a Time
field.
And hold your breath for the work around...
Not to use Time
field type! Just use String
and compare hours and dates via that procedure.
Person.where(:time.gt => "13:00")
If some could explain this weired situation, I would be happy.
Upvotes: 1