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-dTH:i:s", strtotime('September 2, 2021');
 $stDate = new MongoDate(strtotime($stDate));
 $edDate = date("Y-m-dTH:i:s", strtotime('September 7, 2021');
 $edDate = new MongoDate(strtotime($edDate));
 $query = $query->whereBetween('created_at', [$stDate, $edDate]);

Method – 2:
$stDate = date("Y-m-dTH:i:s", strtotime('September 2, 2021');
 $stDate = new MongoDBBSONUTCDateTime(strtotime($stDate));
 $edDate = date("Y-m-dTH:i:s", strtotime('September 7, 2021');
 $edDate = new MongoDBBSONUTCDateTime(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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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 CarbonCarbon;

$stDate = new Carbon('September 2, 2021');
$edDate = new Carbon('September 7, 2021');
$query = $query->whereBetween('created_at', [$stDate, $edDate]);


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x