Reputation: 6502
I've burnt myself out this week pretty bad! I'm failing with fixing a bug which should be solved with some basic mathematics.
I have some "Event" objects in my mongodb database, they get created with a date field, in a pre-save hook I calculate the day of year number and place that onto the model. E.g.
Jan 1st = 1
Jan 5th = 5
Dec 31 = 365
Users of my app can search for events which are X days ahead of the current date. My query is something like:
{
day_number: { $gte: start_day, $lte: end_day}
}
Now the end of the year has come up, there is a logic bug.
Let's say for the inputs Dec 22 to Jan 2
My query is going:
{
day_number: { $gte: 356, $lte: 2}
}
This of course returns no results, as no number is greater than or equal to 356 and less than or equal to 2.
Any suggestions on a fix for this that doesn't involve butchering a albeit broken but simple query?
Upvotes: 0
Views: 39
Reputation: 3149
You could test if the end day is smaller than the start day and then adjust end day like so:
var start_day;
var end_day;
var numDaysInbetween = 0;
var day_number = {}
/* test 1 */
start_day = 50;
end_day = 55;
/* test 2 */
start_day = 356;
end_day = 2;
if (start_day > end_day) {
end_day += 365;
}
day_number = { $gte: start_day, $lte: end_day };
alert(day_number.$lte - day_number.$gte);
Upvotes: 2
Reputation: 6087
A majority of the time calculations in computer systems use the number of milliseconds elapsed since the rather arbitrary date 1970-01-01 0:00 as a sortable time variable.
You could apply the same principle but use the number of days since 2016-01-01, which would make Jan 2 == day 367. This way the query needs no change, your "hook" just needs a small mod.
Upvotes: 1