Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare date with mongodb ISO date in laravel

I am using mongodb with laravel and I have stored date in ISO format in mongodb collection as below

"created_at" : ISODate("2021-09-03T05:48:44Z")

Now, I am taking dates from user and want to fetch the record between the given 2 dates. I tried this with following methods but none of them working in my case. Method - 1:

$stDate = date("Y-m-d\TH:i:s", strtotime('September 2, 2021');
 $stDate = new MongoDate(strtotime($stDate));
 $edDate = date("Y-m-d\TH:i:s", strtotime('September 7, 2021');
 $edDate = new MongoDate(strtotime($edDate));
 $query = $query->whereBetween('created_at', [$stDate, $edDate]);

Method - 2:

$stDate = date("Y-m-d\TH:i:s", strtotime('September 2, 2021');
 $stDate = new \MongoDB\BSON\UTCDateTime(strtotime($stDate));
 $edDate = date("Y-m-d\TH:i:s", strtotime('September 7, 2021');
 $edDate = new \MongoDB\BSON\UTCDateTime(strtotime($edDate));
 $query = $query->whereBetween('created_at', [$stDate, $edDate]);

There are similar questions already available on stack overflow itself and I tried some of the solutions as well but nothing is working in my case. There is no any error generating and I am not getting required output as well. So, can anyone please help me out. Thanks in advance.

like image 221
P N Jain Avatar asked Nov 07 '22 00:11

P N Jain


1 Answers

In Laravel Carbon package can help us to deal with date-time so simply use the Carbon function to convert your date and time like below.

use Carbon\Carbon;

$stDate = new Carbon('September 2, 2021');
$edDate = new Carbon('September 7, 2021');
$query = $query->whereBetween('created_at', [$stDate, $edDate]);
like image 55
Sachin Avatar answered Nov 13 '22 05:11

Sachin