Search code examples
javascriptparse-platform

parse.com - how i can create query equal createdAt by date only with javascript



I want to find data by "createdAt" field but i need to search with date only (without time).
var d = new Date();
var query = new Parse.Query("TableName");
query.equalTo("createdAt", d);

Solution

  • What you basically have to do to generate two dates:

    • date at 0:0:0 time
    • date+1day at 0:0:0 time

    Then search for:

    query.greaterThanOrEqualTo('createdAt', date);
    query.lessThan('createdAt', datePlusOne);
    

    This effectively gives you the range of dateT0:0:0 - dateT23:59:59.99999 inclusive, but in a safe way

    If you want to use pure JavaScript:

    // assuming date is the date/time to start from
     date.setHours(0, 0, 0, 0);
    // hours/min/sec/ms cleared
     var datePlusOne = new Date(date);
     datePlusOne.setDate(datePlusOne.getDate() + 1);
    

    You can also use the moment library to make your code easier to read/maintain. This library is also used server-side in parse.com, though it is an older version.

     m1 = new moment(date);
     m1.startOf('day');
     m2 = new moment(m1);
     m2.add(1, 'day');
    // convert moment back to JavaScript dates
     date = m1.toDate();
     var datePlusOne = m2.toDate();
    

    Full solution using moments:

    var d = new Date();
    var query = new Parse.Query("TableName");
    
    var start = new moment(d);
    start.startOf('day');
    // from the start of the date (inclusive)
    query.greaterThanOrEqualTo('createdAt', start.toDate());
    
    var finish = new moment(start);
    finish.add(1, 'day');
    // till the start of tomorrow (non-inclusive)
    query.lessThan('createdAt', finish.toDate());
    
    query.find.then(function(results) {
      // use results
    });