Comparing dates with mongoDB ISODate format in php

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

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

In php, I get dates in string format

"2013-08-10"

I want all the data for which birth_date 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 request {"birth_date":{"$gte":"2013-08-10"}} , which {"birth_date":{"$gte":"2013-08-10"}} not filter the data correctly.

The following code snippet didn't work either

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

generates a request

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

it didn't work either

 $dateFilter = new MongoDate($inputDate) 

generates a request

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

Please suggest :)

+4
source share
2 answers

The correct way was to use strtotime , as in

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

like class MongoDate in PHP manual

+8
source

Another solution for creating mongoDate , just create a DateTime object and get the timestamp using a DateTime object, and then create a mongoDate object on timestamp

 $time = new DateTime('2013-08-10'); $mongoDate = new MongoDate($currentDateWithTime->getTimestamp()); 
0
source

All Articles