在php中创建每周日历

2022-01-11 00:00:00 calendar php html

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

I have created a php calender which will show one week at a time.Here is the code i have created

 <?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>

当我试图去下周时,它工作正常.但是当年份变化时,它不适用于明年.

when i am trying to go to the next week it is working correctly. But when the year is changing it is not working for the next year.

推荐答案

将周计算留给 DateTime::setIsoDate() 方法.

Leave the week calculation to the DateTime::setIsoDate() method.

这是解决您问题的最简单和最佳的解决方案:

Here is the simplest and best solution for your problem :

<?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>
";
    $dt->modify('+1 day');
} while ($week == $dt->format('W'));
?>
    </tr>
</table>

相关文章