PHP - 从日期获取周数

时间:2016-05-22 03:49:57

标签: php strtotime

我有约会,我想得到那个月的周数,我该怎么做?

我试过了:

$time = '2016/05/21';
echo date("w", strtotime($time));

我也试过W,但这是一年中的一周,但在我的情况下,我需要一个月。

当前结果: 6

欲望结果: 4

2 个答案:

答案 0 :(得分:4)

试试这个。

  function weekOfMonth($date) {
    //Get the first day of the month.
    $firstOfMonth = strtotime(date("Y-m-01", $date));
    //Apply above formula.
    return intval(date("W", $date)) - intval(date("W", $firstOfMonth)) + 1;
  }

您可以在此处查看here

您必须执行

$datee = "2016/08/10";
$datee = strtotime( str_replace("/", "-", $datee));
echo weekOfMonth($datee);

答案 1 :(得分:0)

我在另一个PHP get number of week for month找到了相同的解决方案,请看一下。

function getWeeks($date, $rollover)
{
    $cut = substr($date, 0, 8);
    $daylen = 86400;

    $timestamp = strtotime($date);
    $first = strtotime($cut . "00");
    $elapsed = ($timestamp - $first) / $daylen;

    $weeks = 1;

    for ($i = 1; $i <= $elapsed; $i++)
    {
        $dayfind = $cut . (strlen($i) < 2 ? '0' . $i : $i);
        $daytimestamp = strtotime($dayfind);

        $day = strtolower(date("l", $daytimestamp));

        if($day == strtolower($rollover))  $weeks ++;
    }

    return $weeks;
}

$time = '2016/05/21';
echo getWeeks($time, 'Sunday'); //4