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
1 Answer 1
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>
-
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– Rob Apodaca2013年03月31日 17:27:47 +00:00Commented Mar 31, 2013 at 17:27