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

asked Mar 27, 2013 at 10:58
\$\endgroup\$

1 Answer 1

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>
answered Mar 29, 2013 at 15:24
\$\endgroup\$
1
  • 2
    \$\begingroup\$ +1 very nice. You might consider <th style="width:12%"><?php echo $date->format('D jS) ?></th> to avoid stringified markup \$\endgroup\$ Commented Mar 31, 2013 at 17:27

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.