回显所有月份与日期日历
我使用下面的代码来回显当前月份。我怎样才能增强它,以便显示所有月份的名称、日期和日期..
代码:
<?php
$today = getdate();
$firstDay = getdate(mktime(0,0,0,$today['mon'],1,$today['year']));
$lastDay = getdate(mktime(0,0,0,$today['mon']+1,0,$today['year']));
?>
<?php
echo '<table>';
echo ' <tr><th colspan="7">'.$today['month']." - ".$today['year']."</th></tr>";
echo '<tr class="days">';
echo ' <td>Mo</td><td>Tu</td><td>We</td><td>Th</td>';
echo ' <td>Fr</td><td>Sa</td><td>Su</td></tr>';
?>
<?php
echo '<tr>';
for($i=1;$i<$firstDay['wday'];$i++){
echo '<td> </td>';
}
$actday = 0;
for($i=$firstDay['wday'];$i<=7;$i++){
$actday++;
echo "<td>$actday</td>";
}
echo '</tr>';
?>
<?php
$fullWeeks = floor(($lastDay['mday']-$actday)/7);
for ($i=0;$i<$fullWeeks;$i++){
echo '<tr>';
for ($j=0;$j<7;$j++){
$actday++;
echo "<td>$actday</td>";
}
echo '</tr>';
}
?>
<?php
if ($actday < $lastDay['mday']){
echo '<tr>';
for ($i=0; $i<7;$i++){
$actday++;
if ($actday <= $lastDay['mday']){
echo "<td>$actday</td>";
}
else {
echo '<td> </td>';
}
}
echo '</tr>';
}
?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
试试这个:
它将返回传递给函数的年份的月份->周->日->工作日的数组。希望可以很容易地遍历数组来打印所有内容。我确信您可以对此进行很多调整,但这只是一个开始。
我也会尝试避免使用 echo 打印 html,例如,而不是;
做;
我认为这使得代码更具可读性。
编辑:只是想我还应该包括一个用例的示例,如下所示:
这将为您提供输出:
>
Try this:
it will return an array of months->weeks->day->weekday of the year you pass to the function. Hopefully it should be easy to traverse through the array to print everything out. Am sure there are a lot of tweaks you can make to that but its a start.
I would also try and stay away from printing out html using echo, for example instead of;
do;
It kind of makes the code more readable I think.
EDIT: Just thought I should include an example of a use case as well, as below:
Which gives you the output:
您可以使用此函数将全年转换为数组
调用它,
您将在源代码中看到这一点(月->周->天):
因此,现在可以轻松地使用类似的方法为您需要的每个月创建月份表使用
这些函数,如
..或将月份放入
for
循环中。因此...例如,对于 2011 年 1 月,您会在浏览器中看到此
希望这会有所帮助。
You can use this function to convert entire year into array
Call it like
You'll see this in source (months->weeks->days):
So, now it's easy to create month table for every month you need using something like this
Use these functions like
..or put months in
for
loop.So... e.g. for January 2011 in your browser you'll see this
Hope this helps.
最佳答案有误!如果年份是闰年,则应该在周期之前添加一个条件,否则第一个月第一天的输出将会出现问题 查看屏幕截图。
必要条件:
date("L", mktime(0,0,0, 7,7, $year)) ? $天数 = 366 : $天数 = 365;
(如果年份是闰年,则周期计数器 = 366,否则为 365)
The best answer has an inaccuracy! You should add a condition if year is leap-year BEFORE a cycle, otherwise you will have problems with output of first days of first month see screenshot.
The necessary condition:
date("L", mktime(0,0,0, 7,7, $year)) ? $days = 366 : $days = 365;
(if year is leap-year then counter of cycle = 366 else 365)
将当前代码包装在函数中,然后将带有所需日期的参数传递给它。
Wrap your current code within a function then pass an argument to it with your desired date.