Question

I am having a field in mongoDB, say birth_date which is in ISODate format like

ISODate("2013-08-15T23:00:00Z")

In php, I am getting dates in the string format

"2013-08-10"

I want all the data for which birth_date is greater than 2013-08-10

For this I have a code

$inputDate = "2013-08-10";
$dateFilter = array("\$gte",$inputDate); //works well when birth_date field is normat date string like "2013-08-16" but doesn't work with ISODate format as above
$dateRangeQuery = array("birth_date" => $dateFilter);

which generate the query {"birth_date":{"$gte":"2013-08-10"}} which is not correctly filtering data.

Following code snippet too didn't work

$dateFilter = array("\$gte",date("c", $inputDate)); 

generates the query

{"birth_date":{"$gte":"2013-08-10T00:00:00+05:30"}}

then this too didn't work

$dateFilter = new MongoDate($inputDate)

generates query

{"birth_date":{"$gte":{"sec":2013,"usec":0}}}

Please suggest :)

Was it helpful?

Solution

The correct way was to use strtotime as in

$dateFilter = new MongoDate(strtotime($inputDate))

like MongoDate class in PHP Manual

OTHER TIPS

There another solution to create mongoDate , just create DateTime object and get timestamp using DateTime object then create MongoDate object by timestamp

    $inputDate = new DateTime('2013-08-10');
    $mongoDate = new MongoDate($inputDate->getTimestamp());

In case need to use current DateTime

   $currentDateTime = strtotime('now'); // as This method already ruen timestamp 
   $mongoDate = new MongoDate($currentDateTime);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top