How can I get list of dates of the current month till current date of that month?The Code I have tried so far. I am getting all the dates of this current month.
$month = 12;
$year = 2022;
for($d=1; $d<=31; $d++)
{
$time = mktime(12, 0, 0, $month, $d, $year);
if (date('m', $time) == $month)
$list[]=date('Y-m-d', $time);
}
4
Answers
You can try like this:
This answer works for OP’s original question ("current month") not for the edited answer check the marked as answer one.
There’s no need to compare anything. It’s sufficient to generate a range of days from 1 until today (if current year/month), or the end of the month (custom year/month), and then then iterate over it, appending days (zero-padded) to the
Y-m-
base date. As follows:If generating dates for this year/month, use the
$base = date('Y-m');
date call . For other year/month, use the literal$base = '1980-02';
and generate the day range to match the days in that month. Withdate('t')
to get "days in month", leap years are considered.The first option produces (as of today) the following array:
Note the
str_pad((string) $day
in padding days, where we typecast the$day
number to a string. Why? We are iterating integers, whilestr_pad()
expects a string. If the argument is not a string, aTypeError
will be thrown when coding withdeclare(strict_types=1)
on.The above wrapped in a function to make this convenient. See Demo, Source.
This also should work.