我有一个显示当前月份的日历,我们将其用于日程安排。我们要求将今天的日期放在中间,两边都有两周的日期。
当前代码:
<!DOCTYPE html>
<html>
<head>
<title>Running calendar</title>
</head>
<body>
<?php
date_default_timezone_set('America/New_York');
//Get today's date
$date = time();
//Break date into separate values
$day = date('d',$date);
$month = date('m',$date);
$year = date('Y',$date);
//Generate first day of the month
$first_day = mktime(0,0,0,$month,1,$year);
//Grab month name
$title = date('F',$first_day);
//Here you find out what day of the week the first day of the month falls on
$day_of_week = date('D', $first_day) ;
//We then determine how many days are in the current month
$days_in_month = cal_days_in_month(0, $month, $year) ;
switch($GLOBALS['day_of_week'])
{
case "Sun": $blank = 0; break;
case "Mon": $blank = 1; break;
case "Tue": $blank = 2; break;
case "Wed": $blank = 3; break;
case "Thu": $blank = 4; break;
case "Fri": $blank = 5; break;
case "Sat": $blank = 6; break;
}
$currHour = date("H");
echo "<div id=container>";
echo "<table width=100% class=calendar>";
echo "<tr><th colspan=32 id=title>$title $year</th></tr>";
echo "<tr><th>Employee</th>";
$day_num=1;
while($day_num <= $days_in_month){
echo "<th align=center ";
if($day == $day_num){echo "id=day";}
echo ">$day_num</th>";
$day_num++;
}
echo "</tr>";
echo "</table>";
echo "</div>";
?>
</body>
</html>
他们希望看到什么:
21 22 23 24 25 26 27 28 29 30 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
我没有任何运气能够让代码在过去两周内正确显示。
答案 0 :(得分:1)
最干净的选择可能如下:
$period = new \DatePeriod(
new \DateTime('-14 days'),
\DateInterval::createFromDateString('1 day'),
new \DateTime('+14 days')
);
foreach ($period as $day) {
print $day->format("d") . " | ";
}
输出是:
21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 01 | 02 | 03 | 04 | 05 | 06 | 07 | 08 | 09 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |
如果你今天必须做一些事情而循环,只需用等号检查抓住它:
if($day == new \DateTime()){
print "<span style='background-color:red;'>".$day->format("d") . "</span> | ";
}else{
print $day->format("d") . " | ";
}
答案 1 :(得分:0)
您只需要更改计算开始日期的方式以及您希望显示的天数。
对于开始日期,只需更改此内容:
$first_day = mktime(0,0,0,$month,1,$year);
为:
// Substract 14 days from the $date
$first_day = $date - (60 * 60 * 24 * 14);
您需要将while
循环更改为从此日期开始并运行28(?)次。
答案 2 :(得分:0)
我使用for
循环和DateTime
并提出了这个:
<?php
for ($i = 14; $i > 0; $i--) {
echo ' '. DateTime::createFromFormat('U', time())
->modify('-' . $i . ' days')
->format('d');
}
echo PHP_EOL;
$now = new DateTime();
echo $now->format('d');
echo PHP_EOL;
for ($i = 1; $i <= 14; $i++) {
echo ' '. DateTime::createFromFormat('U', time())
->modify('+' . $i . ' days')
->format('d');
}
输出:
21 22 23 24 25 26 27 28 29 30 01 02 03 04
05
06 07 08 09 10 11 12 13 14 15 16 17 18 19
您可以更改DateTime::format
中的values以提供更多信息,例如: ->format('d/m')
也可以打印月份。
希望这有帮助。