【问题标题】:Converting day of week to dates for the current month with MYSQL & PHP使用 MYSQL 和 PHP 将星期几转换为当月的日期
【发布时间】:2017-01-08 07:54:14
【问题描述】:

花了一段时间搜索,但找不到任何答案。我希望这个问题很简单。

在我的数据库中,我有一个字符串列 dayOfWeek。

我使用它来跟踪每周安排的每周活动的哪一天。通常我会使用 PHP 将 dayOfWeek 与当天匹配并显示正确的事件。

我想要做的是显示一个未来的日历,它列出了每周重复事件的未来日期。

例如,如果活动在星期二举行,而 2017 年 2 月的星期二是 7 日、14 日、21 日和 28 日。我想用 PHP 来显示。

我知道 strtotime() 用来做相反的事情,从日期中找到一天,但是相反的事情可以轻松完成吗?

抱歉,如果我的问题措辞不当或缺少信息。

【问题讨论】:

  • 那么,如果您的数据库中有星期二,那么您是在寻找未来星期二发生的所有日期还是只针对给定月份?
  • @learner 这两个输出我都会用到。如果我能得到未来的所有日期,那么我可以根据一些变量(接下来的四个日期、给定月份的所有日期等)来限制它们的输出

标签: php mysql date strtotime


【解决方案1】:

2017 年 2 月星期二的用例

$n=date('t',strtotime("2017-02-01")); // find no of days in this month
$dates=array();
for ($i=1;$i<=$n;$i++){
     $day=date("D",strtotime("2017-02-".$i)); //find weekdays

    if($day=="Tue"){
        $dates[]="2017-02-".$i;
    }
}
print_r($dates);

http://phpfiddle.org/main/code/s8wq-xx44

【讨论】:

    【解决方案2】:

    你可以这样做:

    // The day of the week.
    $dayOfEvent = row['day'];
    // Say, you wanted the next 5 weeks. 
    $numberOfWeeks = 5;
    $tempDate = date(U);
    $counter = 0;
    
    do{
        $tempDate = $tempDate + 86,164;
        if(date('D', $tempDay) == 'Tue'){
            echo date('l jS \of F Y', $tempDay);
            $counter++;
        }
    }while($counter < $numberOfWeeks);
    

    【讨论】:

      【解决方案3】:

      首先尝试查找当前星期的日期。之后继续添加 7 天的倍数。

      <?php 
          // $timestamp = now();
      
          for ($i=0; $i < 7; $i++) { 
      
              $days = $i." days";
              $t = date('Y-m-d', strtotime($days));
              $dayOfTheDay = date("D",strtotime($t));
              if ( $dayOfTheDay == day from table )
              {
                  $current_date = $t;
                  break;
              } 
          }
      
          for ($i=0; $i < 200; $i++) { 
              in this loop add 7 days to current_date
          }
       ?>
      

      【讨论】:

        猜你喜欢
        • 2014-01-11
        • 1970-01-01
        • 2011-01-29
        • 2020-01-23
        • 2020-12-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-01
        相关资源
        最近更新 更多