1
\$\begingroup\$

I'm trying to get to grips with the DateTime class in PHP. Previously I've used date() and mktime() when playing with dates.

Here's the head of a calendar table, and I'm pretty sure I'm doing this in a stupid way! That fact that I'm setting the format each time, and modifying the original date with each Interval, seems 'lumpy':

<table class="twelve">
<thead>
<tr>
<?php $date = new DateTime('2013-04-01'); ?>
<th style="width:16%"><?php echo $date->format('Y'); ?></th>
<th style="width:12%"><?php echo $date->format('D jS');?></th>
<th style="width:12%"><?php $date->add(new DateInterval('P1D')); echo $date->format('D jS');?></th>
<th style="width:12%"><?php $date->add(new DateInterval('P1D')); echo $date->format('D jS');?></th>
<th style="width:12%"><?php $date->add(new DateInterval('P1D')); echo $date->format('D jS');?></th>
<th style="width:12%"><?php $date->add(new DateInterval('P1D')); echo $date->format('D jS');?></th>
<th style="width:12%"><?php $date->add(new DateInterval('P1D')); echo $date->format('D jS');?></th>
<th style="width:12%"><?php $date->add(new DateInterval('P1D')); echo $date->format('D jS');?></th>
</tr>
</thead>
</table>

Can anyone point me towards a better way to do this. I'm planning to create a function to spit these calendars out, but I've provided an inline example here so you can see the way I'm using DateTime etc for now.

Thanks

\$\endgroup\$
2
\$\begingroup\$

I like it. You could use loops and use a variable for 'DateInterval(P1D)'.

<table class="twelve">
<thead>
<tr>
<?php $date = new DateTime('2013-04-01'); 
      $day = new DateInterval('P1D');
?>
<th style="width:16%"><?php echo $date->format('Y'); ?></th>
<th style="width:12%"><?php echo $date->format('D jS');?></th>
<?php 
for($i = 0;$i <= 6; $i++){
    $date->add($day)
    echo '<th style="width:12%">'.$date->format('D jS').'</th>';
}?>
</tr>
</thead>
</table>
\$\endgroup\$
  • 2
    \$\begingroup\$ +1 very nice. You might consider <th style="width:12%"><?php echo $date->format('D jS) ?></th> to avoid stringified markup \$\endgroup\$ – Rob Apodaca Mar 31 '13 at 17:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.