Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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") }});
like image 664
Daihatsu Coure Avatar asked Jan 19 '26 00:01

Daihatsu Coure


1 Answers

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

like image 138
Remon van Vliet Avatar answered Jan 22 '26 18:01

Remon van Vliet