我正在编写一个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天内做这个吗?
答案 0 :(得分:0)
如此处所述: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));
答案 1 :(得分:0)
我不确定您是否需要使用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);
}
?>