Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comparing date with mongoDB ISODate format in php

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 :)

like image 280
veer7 Avatar asked Dec 15 '22 05:12

veer7


2 Answers

The correct way was to use strtotime as in

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

like MongoDate class in PHP Manual

like image 168
veer7 Avatar answered Dec 30 '22 12:12

veer7


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);
like image 35
ahmed hamdy Avatar answered Dec 30 '22 13:12

ahmed hamdy