dpwgzi7987 2012-09-04 13:48
浏览 15

PHP在一个表中列出本周的日期,可以使用按钮将其更改为显示在下周或上周

I am trying to get a calendar up and running. Even though I'm not that great with PHP I managed to get a monthly view calendar up and running quite nicely. However, the goal posts have been moved somewhat and the powers that be would like a weekly view calendar. When they open it will show all of the days of the current week in a table and then have the option to go forward a week and show the next week or back a week. I have struggled with this for many days and my code has gotten over complicated and messy when I am sure there must be a simple solution.

I know that this is a big ask but I will be so grateful if someone could point me in the right direction or give me a simple script for me to build on so I can get back to living my life

This is what I have so far

$week_number = date("W");
$year = date("Y");

if($week_number < 10){
   $week_number = "0".$week_number;
}

for($day=0; $day<=6; $day++)
{
  echo date('d-m-Y', strtotime($year."W".$week_number.$day))." | 
";
}
?>

I managed to get it up and running in a fashion by adding 1 to the $week_number if the 'next_week' button and been clicked (part of a self posting form I haven't included to keep the script simple ) which worked well until the year changed because the week numbers carried on past 53 and I haven't added a way to make $year increase or decrease That's where it all went wrong

  • 写回答

1条回答 默认 最新

  • dongzhi6087 2014-04-26 04:28
    关注

    DateTime and DateInterval are your friends (PHP 5.3+)

    Give this a go:

    <?php
    
    $weekModifier = 0;
    
    $date = new DateTime();
    
    if($date->format('N') !== 1) {
        $date->sub(new DateInterval('P'. $date->format('N') . 'D'));
    }
    
    $interval = new DateInterval('P'.abs($weekModifier).'W');
    
    if($weekModifier > 0) {
        $date->add($interval);  
    } else {
        $date->sub($interval);  
    }
    
    for($i = 1; $i <= 7; $i++) {
        echo $date->add(new DateInterval('P1D'))->format('l Y-m-d') . "<br>
    "; 
    }
    
    ?>
    

    Leaving the week at 0 will use this week. Otherwise, you can simply use 1, 2, 3, -,1 ,-2, -3 etc...

    See it in action.

    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么