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 this idate('m') 1 ou -1 occur, the result can be 0 or 13, which doesn't exist. Is there a diferent 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 it's really subtracting days instead of the actual month.
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.
No conditions are necessary.
$d = new DateTime('first day of this month');
$d->modify("$request month");
$query->where(
['month', '=', $d->format('Y')],
['year', '>=', $d->format('n')]
);
CodePudding user response:
use this code
<?php
$month = null;
if ($request->flagMonth == -1) {
$month = date('m',strtotime("-1 months"));
}
elseif ($request->flagMonth == 0) {
$month = date('m');
}
elseif ($request->flagMonth == 1) {
$month = date('m',strtotime(" 1 months"));
}
if ($month) {
$query->where(
['month', '=',$month],
['year', '>=', (idate('Y')-1)]
);
}