【问题标题】:MYSQL - Selecting Dates of Current Work WeekMYSQL - 选择当前工作周的日期
【发布时间】:2016-03-18 19:44:18
【问题描述】:

我正在编写一个 PHP 程序,它将获取当前工作周(不包括星期一)的所有日期。我的代码如下:

//Get Year
$sql = "SELECT YEAR(CURDATE()) AS CurYear";
$result = mysqli_query($db, $sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$curyear = $row['CurYear'];
//Get Week
$sql = "SELECT WEEK(CURDATE()) AS CurWeek";
$result = mysqli_query($db, $sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$curweek = $row['CurWeek'];
//Get Date of Tuesday
$sql = "SELECT STR_TO_DATE('$curyear$curweek Tuesday', '%X%V %W') AS TueDate";
$result = mysqli_query($db, $sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$tuedate = $row['TueDate'];

它可以工作并且会返回这个星期二的日期,但是有没有更有效的方法来做到这一点,而且在接下来的 3 天里做到这一点?

【问题讨论】:

  • 为什么要使用 MySQL 而不是直接在 PHP 中执行此操作?

标签: php mysql datetime


【解决方案1】:

如此处所述:How to find the day of week from a date using PHP? 你可以使用 date 命令:

$time = time(); // present time
$day  = 3; //the day of the week we are looking for 0: sunday, 1 monday and so on
$dayofweek = date('w', $time); //current day week number
$result  = date('Y-m-d', strtotime(($day - $dayofweek).' day', $time));

【讨论】:

    【解决方案2】:

    我不确定您是否需要使用 MySQL,但我会直接在 PHP 中执行此操作。以下是您如何处理它的示例。设置变量$TuesTS 后,您可以通过添加(24*60*60)86400 来计算第二天,即一天中的秒数。

    <?php
        $ts = time();
        $todayNum = date('N');
        if ( ($todayNum >= 2) && ($todayNum<=5)){
            $offset = $todayNum - 2; // number of days after Tuesday;
            $TuesTS = $ts-($offset*24*60*60);
    
            echo "Tuesday : ".date('Y-m-d', $TuesTS);
        }
    ?>
    

    【讨论】:

      猜你喜欢
      • 2020-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-25
      • 2013-08-22
      • 1970-01-01
      • 2011-10-04
      相关资源
      最近更新 更多