blackrx
blackrx

Reputation: 81

generate monthly date from 1st to 1st

the code below will generate day for each and month.. How do i list the date until the first day of the following month...

example 1st January to 1st February, 1st May to 1st June...etc

<?php

$month = "01";
$year = "2017";

$start_date = "01-".$month."-".$year;
$start_time = strtotime($start_date);

$end_time = strtotime("+1 month", $start_time);

echo "<table border='1'>";

for($i=$start_time; $i<$end_time; $i+=86400)
{
$list = date('Y-m-d-D', $i);
echo "<tr><td>";
echo $list;
echo "</td><td> </td></tr>";

}

echo "</table>";

?>

Upvotes: 1

Views: 39

Answers (1)

icecub
icecub

Reputation: 8783

First you create a function so you can use it again without having to duplicate code. Read the comments inside to see what each line does.

<?php

function genMonthTable($month, $year){
    /* Get days in month */
    $days = cal_days_in_month(CAL_GREGORIAN, $month, $year);

    /* Add 1 extra day to get first day of the next month */
    $days+=1;

    /* Instantiate DateTime object */
    $date = new DateTime();

    /* Set date */
    $date->setDate($year, $month, 1);

    /* Create table */
    echo "<table style='border: 1px solid black;'><tbody>";

    /* Loop table rows */
    for($i = 1; $i <= $days; $i++){
        echo "<tr><td>";
        echo $date->format('Y-m-d');
        echo "</td></tr>";

        /* Increate date by 1 day */
        $date->modify('+1 day');
    }

    /* Finish table */
    echo "</tbody></table>";

    /* Unset DateTime object */
    unset($date);
}

/* Generate table for Januari 2017 */
genMonthTable(1, 2017);

/* Generate table for May 2017 */
genMonthTable(5, 2017);

?>

Upvotes: 1

Related Questions