在php中创建每周日历

时间:2013-09-18 09:11:02

标签: php html calendar

我创建了一个php日历,一次显示一周。这是我创建的代码

 <?php
   $week = date("W");
   $year = (isset($_GET['year']))?$_GET['year']:date("Y");
   $week = (isset($_GET['week']))?$_GET['week']:Date('W');
   if($week>53){
     $year+= 1;
     $week=1;
   }
 ?>

 <a href="<?php echo $_SERVER['PHP_SELF'].'?week='.($week+1).'&year='.$year; ?>">Next  Week</a> <!--Next week-->

 <a href="<?php echo $_SERVER['PHP_SELF'].'?week='.($week-1).'&year='.$year; ?>">Pre Week</a> <!--Previous week-->

 <table border="1px">
 <tr>
 <td>Employee</td>
 <?php
 for($day=1; $day<=7; $day++)
 {
    $d = strtotime($year."W".$week.$day);                           
    echo "<td>".date('l',$d )."<br>";
    echo date('d M',$d)."</td>";
 }
 ?>
 </tr>

当我试图去下周时,它正常工作。但是,当这一年正在发生变化时,它将在明年不起作用。

2 个答案:

答案 0 :(得分:12)

将周计算保留为DateTime::setIsoDate()方法。

以下是针对您的问题的最简单和最佳解决方案:

<?php
$dt = new DateTime;
if (isset($_GET['year']) && isset($_GET['week'])) {
    $dt->setISODate($_GET['year'], $_GET['week']);
} else {
    $dt->setISODate($dt->format('o'), $dt->format('W'));
}
$year = $dt->format('o');
$week = $dt->format('W');
?>

<a href="<?php echo $_SERVER['PHP_SELF'].'?week='.($week-1).'&year='.$year; ?>">Pre Week</a> <!--Previous week-->
<a href="<?php echo $_SERVER['PHP_SELF'].'?week='.($week+1).'&year='.$year; ?>">Next Week</a> <!--Next week-->

<table>
    <tr>
        <td>Employee</td>
<?php
do {
    echo "<td>" . $dt->format('l') . "<br>" . $dt->format('d M Y') . "</td>\n";
    $dt->modify('+1 day');
} while ($week == $dt->format('W'));
?>
    </tr>
</table>

答案 1 :(得分:2)

当您使用strtotime时,您的周必须两位数。如果在for循环之前周低于10,则必须前置零。

if($week < 10) {
    $week = '0'. $week;
}
for($day = 1; $day <= 7; $day++) {

另外,一年只有52周,开始的条件应该是。

if($week > 52) {
    $year++;
    $week = 1;
} elseif($week < 1) { // If you want the possibility to go back too
    $year--;
    $week = 52;
}

完整代码:

<?php
$year = (isset($_GET['year'])) ? $_GET['year'] : date("Y");
$week = (isset($_GET['week'])) ? $_GET['week'] : date('W');
if($week > 52) {
    $year++;
    $week = 1;
} elseif($week < 1) {
    $year--;
    $week = 52;
}
?>

<a href="<?php echo $_SERVER['PHP_SELF'].'?week='.($week == 52 ? 1 : 1 + $week).'&year='.($week == 52 ? 1 + $year : $year); ?>">Next  Week</a> <!--Next week-->
<a href="<?php echo $_SERVER['PHP_SELF'].'?week='.($week == 1 ? 52 : $week -1).'&year='.($week == 1 ? $year - 1 : $year); ?>">Pre Week</a> <!--Previous week-->

<table border="1px">
    <tr>
        <td>Employee</td>
<?php
if($week < 10) {
    $week = '0'. $week;
}
for($day= 1; $day <= 7; $day++) {
    $d = strtotime($year ."W". $week . $day);

    echo "<td>". date('l', $d) ."<br>". date('d M', $d) ."</td>";
}
?>
    </tr>
</table>