Friday, 19 June 2015

PHP: Date function to display all dates between two dates

There is the DatePeriod class.
EXAMPLE:
$begin = new DateTime('2013-02-01');
$end = new DateTime('2013-02-13');

$daterange = new DatePeriod($begin, new DateInterval('P1D'), $end);

foreach($daterange as $date){
    echo $date->format("Y-m-d") . "<br>";
}
(P1D stands for period of one day, see DateInterval for further documentation)
Example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
table,th,td{
    border:1px solid black;
}
th,td{
    height:40px;
    width:140px;
    font-weight:bold;
}
</style>
</head>

<body>
<?php
$start_date = date('Y-m-d',time()-84600);
//echo date('d/m/Y', strtotime('+2 months'));
//echo date('M d Y',$date);
$end_date = date('Y-m-d',strtotime('+3 months'));
//echo date('d/m/Y', strtotime('+1 day'));

//echo strtotime('+1 day');
$begin = new DateTime($start_date);
$end = new DateTime($end_date);

$daterange = new DatePeriod($begin, new DateInterval('P1D'), $end);


?>
<table cellpadding="0" cellspacing="0" width="100%">
    <thead>
        <tr>
                <th>#</th>
                <td>Date</td>
                <td>SM</td>
                <td>Auditing</td>
                <td>Accounts</td>
                <td>IT</td>
        </tr>
    </thead>
    <tbody>
    <?php
    $i=1;
    foreach($daterange as $date){ ?>
        <tr>
            <td rowspan="2"><?php  echo $i; ?></td>
            <td rowspan="2"><?php  echo $date->format("M d Y"); ?></td>
            <td>test</td>
            <td>test</td>
            <td>test</td>
            <td>test</td>
        </tr>
        <tr>
            <td>test</td>
            <td>test</td>
            <td>test</td>
            <td>test</td>
        </tr>
       
        <?php $i++; } ?>
    </tbody>
</table>
</body>
</html>


Another way:
<?php 
  $day = 86400; // Day in seconds  
        $format = 'Y-m-d'; // Output format (see PHP date funciton)  
        $sTime = strtotime($start_date); // Start as time  
        $eTime = strtotime($end_date); // End as time  
        $numDays = round(($eTime - $sTime) / $day) + 1;  
        $days = array();  

        for ($d = 0; $d < $numDays; $d++) {  
            $days[] = date($format, ($sTime + ($d * $day)));  
        }  
 ?>


0 comments:

Post a Comment