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.
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With