Daihatsu Coure
Daihatsu Coure

Reputation: 33

comparing dates to retrieve data

I have data something like this in mongodb

{ "_id" : ObjectId("4f0ee7310b09f7a254000001"), "createdAt" : ISODate("2012-01-12T23:58:28Z") }
{ "_id" : ObjectId("4f0ee7350b09f7a254000002"), "createdAt" : ISODate("2012-01-12T23:58:28Z") }
{ "_id" : ObjectId("4f0ee855e63cecb654000001"), "createdAt" : ISODate("2012-01-13T00:03:59Z") }
{ "_id" : ObjectId("4f0ee859e63cecb654000002"), "createdAt" : ISODate("2012-01-13T00:04:08Z") }
{ "_id" : ObjectId("4f0ee97c212d70bc54000001"), "createdAt" : ISODate("2012-01-13T00:08:54Z") }
{ "_id" : ObjectId("4f0ee99f212d70bc54000002"), "createdAt" : ISODate("2012-01-13T00:09:27Z") }

I want to show only the record based on date. Check my code its returning me nothing

//dateStr = '120112' or '120113'
var year = '20' + dateStr.substring(0,2);
var month =  dateStr.substring(2,4);
var day =  dateStr.substring(4);
dateStr = new Date(year,month,day,0,0,0);

var nextDate = new Date(year,month,day,23,59,59);

GPSData.find({"createdAt" : { $gte : dateStr, $lte:  nextDate }}, function(err, data) {
    if(err)
        console.log(err); 

    res.writeHead(200, {
            "Content-Type": "application/json",
            "Access-Control-Allow-Origin": "*"
    });
    var body = JSON.stringify(data);
    res.end(body);  //no output here just []
});

but on mongo shell using this command I am getting results for date '120112'

db.gpsdatas.find({"createdAt" : {new ISODate("2012-01-12T00:00:00Z"), $lte: new ISODate("2012-01-12T23:59:59Z") }});

Upvotes: 3

Views: 4400

Answers (2)

Remon van Vliet
Remon van Vliet

Reputation: 18595

Your problem is your understanding of the Date class. I'm assuming you're trying to create a date object for the 12th of January but new Date(2012, 1, 12) is actually the 11th or 12th of February depending on local timezone. As such your code doesn't perform the query you're doing in the shell.

Read up on details here http://www.w3schools.com/jsref/jsref_obj_date.asp

Upvotes: 1

StevenLooman
StevenLooman

Reputation: 381

Blind answer, without any testing by myself: What happens if add this line before the GPSData.find(..) line?

dateStr = dateStr.toString();
nextDate = nextDate.toString();

Also, try a console.log to see how the output string looks. It might be in a complete different format than you expect.

Upvotes: 0

Related Questions