1

I am going through the answer of this question in order to loop through first and last day of the current month in php.

I copy-pasted the same code from the answer of the above question but it doesn't seems to return anything (blank).

<?php 
    $current_month_first_day = date('Y-m-01'); // first day of the current month
    $current_month_last_day  = date('m-t-Y');  // last day of the current month
    $interval = DateInterval::createFromDateString('1 day');
    $period = new DatePeriod($current_month_first_day, $interval, $current_month_last_day);
?>  

Problem Statement:

I am wondering what changes I should make in the php code above so that it shows the list of dates from (February 1st to February 29th) for the current month. My code will show dates in input format.

flash
  • 1,455
  • 11
  • 61
  • 132

1 Answers1

2

You're not generating the inputs for the DatePeriod constructor correctly. The first input needs to be a DateTime object, and the third an integer (or another DateTime object). Utilising the first form of the constructor (with the third parameter an integer representing the number of recurrences), you can change your code to this to make it work:

$current_month_first_day = new DateTime('first day of this month'); // first day of the current month
$current_month_last_day  = date('t');  // last day of the current month
$interval = new DateInterval('P1D');
$period = new DatePeriod($current_month_first_day, $interval, $current_month_last_day - 1);

Demo on 3v4l.org

Nick
  • 138,499
  • 22
  • 57
  • 95
  • Thanks for the answer. Its working perfectly fine. I am wondering why did you do `-1` in $period ? – flash Feb 04 '20 at 16:23
  • 1
    @flash the reason for -1 is that the third parameter is the number of dates to be produced, *not including* the first date. So if you used the number of days in the month, you will get one too many days produced since the first of the month is not included in that number. – Nick Feb 04 '20 at 21:18
  • I have one more [question](https://stackoverflow.com/questions/60101194/compare-two-json-objects-array-and-print-specific-content-in-php?noredirect=1#comment106298218_60101194) Its not similar. I am wondering if you can have a look. – flash Feb 06 '20 at 19:57