PHP本周的工作日,为什么date()和strtotime会占用下周


PHP weekdays of current week, why is date() and strtotime taking next week?

我使用以下代码来获得工作日的Y-m-d格式:

$monday = date('Y-m-d', strtotime('Monday'));
$tuesday = date('Y-m-d', strtotime('Tuesday'));
$wednesday = date('Y-m-d', strtotime('Wednesday'));
$thursday = date('Y-m-d', strtotime('Thursday'));
$friday = date('Y-m-d', strtotime('Friday'));

今天是2012-08-01(第31周),我需要的星期一数值应该是2012-07-30。

为什么strtotime('Monday')会在下周一?

因为date('Y-m-d')返回今天的日期,即8月份。您正在将monday转换为time。现在时间用date(Y-m-d)表示(2012年8月)。。因此,显而易见的答案是从今天开始的下周一。

所以要获得上周的日期,请使用

$monday=date(Y-m-d,strtotime('monday this week'))

对于我的应用程序,我只需要为当前星期的日期创建变量。

这就是为什么我使用这个代码:

$mon_value= date('Y-m-d', strtotime('Monday this week'));
$tue_value= date('Y-m-d', strtotime('Tuesday this week'));
$wed_value= date('Y-m-d', strtotime('Wednesday this week'));
$thu_value= date('Y-m-d', strtotime('Thursday this week'));
$fri_value= date('Y-m-d', strtotime('Friday this week'));

它总是在类型的第二天返回。下周一是08-06,下周四是08-02。

<?php
  function getDateOfWeekDay($day) {
    $weekDays = array(
      'Sunday',
      'Monday',
      'Tuesday',
      'Wednesday',
      'Thursday',
      'Friday',
      'Saturday',
    );
    $dayNumber = array_search($day, $weekDays);
    $currentDayNumber =  date('w', strtotime('today'));
    if ($dayNumber > $currentDayNumber) {
      return date('Y-m-d', strtotime($day));
    } else {
      return date('Y-m-d', strtotime($day) - 604800);
    }
  }
  echo  getDateOfWeekDay('Monday');
?>