php实现日历周末变红
实现日历周末变红的方法
使用PHP实现日历中周末日期显示为红色,可以通过判断日期是否为周六或周日,然后应用CSS样式来实现。以下是具体步骤:
获取当前月份的天数和第一天是星期几
$year = date('Y');
$month = date('m');
$days_in_month = date('t', mktime(0, 0, 0, $month, 1, $year));
$first_day = date('w', mktime(0, 0, 0, $month, 1, $year));
生成日历表格
echo '<table border="1">';
echo '<tr><th>Sun</th><th>Mon</th><th>Tue</th><th>Wed</th><th>Thu</th><th>Fri</th><th>Sat</th></tr>';
$day_count = 1;
echo '<tr>';
for ($i = 0; $i < 7; $i++) {
if ($i < $first_day) {
echo '<td></td>';
} else {
$current_date = "$year-$month-$day_count";
$day_of_week = date('w', strtotime($current_date));
$style = ($day_of_week == 0 || $day_of_week == 6) ? 'style="color:red;"' : '';
echo "<td $style>$day_count</td>";
$day_count++;
}
}
echo '</tr>';
填充剩余日期
while ($day_count <= $days_in_month) {
echo '<tr>';
for ($i = 0; $i < 7; $i++) {
if ($day_count > $days_in_month) {
echo '<td></td>';
} else {
$current_date = "$year-$month-$day_count";
$day_of_week = date('w', strtotime($current_date));
$style = ($day_of_week == 0 || $day_of_week == 6) ? 'style="color:red;"' : '';
echo "<td $style>$day_count</td>";
$day_count++;
}
}
echo '</tr>';
}
echo '</table>';
使用CSS样式优化
可以在HTML头部定义CSS样式,使代码更清晰:
<style>
.weekend {
color: red;
}
</style>
然后在PHP代码中动态添加类:
$day_of_week = date('w', strtotime($current_date));
$class = ($day_of_week == 0 || $day_of_week == 6) ? 'weekend' : '';
echo "<td class='$class'>$day_count</td>";
完整示例代码
<?php
$year = date('Y');
$month = date('m');
$days_in_month = date('t', mktime(0, 0, 0, $month, 1, $year));
$first_day = date('w', mktime(0, 0, 0, $month, 1, $year));
?>
<style>
.weekend {
color: red;
}
table {
border-collapse: collapse;
}
td, th {
padding: 8px;
text-align: center;
}
</style>
<table border="1">
<tr>
<th>Sun</th><th>Mon</th><th>Tue</th><th>Wed</th><th>Thu</th><th>Fri</th><th>Sat</th>
</tr>
<tr>
<?php
$day_count = 1;
for ($i = 0; $i < 7; $i++) {
if ($i < $first_day) {
echo '<td></td>';
} else {
$current_date = "$year-$month-$day_count";
$day_of_week = date('w', strtotime($current_date));
$class = ($day_of_week == 0 || $day_of_week == 6) ? 'weekend' : '';
echo "<td class='$class'>$day_count</td>";
$day_count++;
}
}
?>
</tr>
<?php
while ($day_count <= $days_in_month) {
echo '<tr>';
for ($i = 0; $i < 7; $i++) {
if ($day_count > $days_in_month) {
echo '<td></td>';
} else {
$current_date = "$year-$month-$day_count";
$day_of_week = date('w', strtotime($current_date));
$class = ($day_of_week == 0 || $day_of_week == 6) ? 'weekend' : '';
echo "<td class='$class'>$day_count</td>";
$day_count++;
}
}
echo '</tr>';
}
?>
</table>
注意事项
- 代码中的
date('w')返回星期几的数字,0表示周日,6表示周六。 - 可以根据需要调整CSS样式,比如改变字体大小、背景色等。
- 如果需要显示其他月份的日历,可以修改
$year和$month变量的值。







