I need to do some checks with some dates in PHP to retrieve data from the database based on what the user chooses, so I'm using this code:
if ($request->flagMonth == -1) {
$query->where(
['month', '=', (idate('m')-1)],
['year', '>=', (idate('Y')-1)]
);
}
if ($request->flagMonth == 0) {
$query->where(
['month', '=', idate('m')],
['year', '=', idate('Y')]
);
}
if ($request->flagMonth == 1) {
$query->where(
['month', '=', (idate('m') 1)],
['year', '>=', idate('Y')]
);
}
The problem is: when the idate('m')
is 1
or -1
, the result can be 0
or 13
-- which of course are not valid month values.
Is there a different function I can call to operate with dates?
CodePudding user response:
As noted, you're using idate
to get the numerical month, which of course when you subtract or add, it's not going to roll over because it's just a number. The best way to go about it would be to use DateTime, or since you're using Laravel, Carbon, to create a date, do the math, then get the numbers you're looking for. Laravel uses now()
as a shortcut for Carbon::now()
if ($request->flagMonth == -1) {
$now = now()->firstOfMonth()->subMonth();
$query->where(
['month', '=', $now->month],
['year', '>=', $now->year]
);
}
else if ($request->flagMonth == 0) {
$query->where(
['month', '=', now()->month],
['year', '=', now()->year]
);
}
else if ($request->flagMonth == 1) {
$now = now()->firstOfMonth()->addMonth();
$query->where(
['month', '=', $now->month],
['year', '>=', $now->year]
);
}
Note that I used firstOfMonth
when adding or subtracting. This is because when you get to the end of the month, it gets wonky since not all day numbers exist in all months.
CodePudding user response:
Create a datetime object from the first day of the current month, then modify the date using $request->flagMonth
, then call format()` to access the desired part of the adjusted date. This precaution of using the first day of the month prevent buggy effects as mentioned here.
No conditions are necessary.
$d = new DateTime('first day of this month');
$d->modify("$request month");
$query->where(
['month', '=', $d->format('n')],
['year', '=', $d->format('Y')]
);