I want to get data inserted in previous week in Laravel 5.1. Currently I am using following query:
$AgoDate=\Carbon\Carbon::now()->subWeek()->format('Y-m-d'); // returns 2016-02-03
$NowDate=\Carbon\Carbon::now()->format('Y-m-d'); // returns 2016-02-10
$query->whereBetween('created_on', array($AgoDate,$NowDate));
This returns last 7 days data, but I need last week's data, which means it should return data from 31st Jan to 6th Feb, i.e. the previous week.
Note: in my case Week starts from Sunday and ends on Saturday.
EDIT: adjusting to OP's question
For ago date use
$currentDate = \Carbon\Carbon::now();
$agoDate = $currentDate->subDays($currentDate->dayOfWeek)->subWeek();// gives 2016-01-31
Similarly you can get your nowDate
$currentDate = \Carbon\Carbon::now();
$nowDate = $currentDate->subDays($currentDate->dayOfWeek + 1); // gives 2016-02-06
to adjust the weekstart(sunday/monday) I think you can add/subtract some days to dayOfWeek e.g $currentDate->subDays($currentDate->dayOfWeek + 1 /* or -1 */);
EDIT : as mentioned in the comments you can also use startOfWeek()
method instead of subDays()
if it works directly for you.
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