Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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
});

Solution 2:

If you are looking for results, filtered by "created today", you could do this:

var moment = require("moment");
var start = moment().sod() //Start of day
var end = moment().eod() //End of day

var query = new Parse.Query("myClass")
query.greaterThanOrEqualTo("createdAt", start.format());
query.lessThan("createdAt", end.format());
query.find({...});

Of course, if you are looking for a greater timespan than "today", you would go with Timothy's answer.

This code has been tested in Parse Cloud Code with Momentjs 1.7.2


Post a Comment for "Parse.com - How I Can Create Query Equal CreatedAt By Date Only With Javascript"