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?
My Answer:
>input('date_type') == 'current_month') {
$start_date = date('Y-m-01');
$end_date = date('Y-m-t');
} elseif ($request->input('date_type') == 'previous_month') {
$start_date = date('Y-m-01', strtotime('first day of last month'));
$end_date = date('Y-m-t', strtotime('last day of last month'));
} elseif ($request->input('date_type') == 'next_month') {
$start_date = date('Y-m-01', strtotime('first day of next month'));
$end_date = date('Y-m-t', strtotime('last day of next month'));
}
echo "Start Date: " . $start_date . "
";
echo "End Date: " . $end_date;
Rate this post
4 of 5 based on 6278 votesComments