获取本周的第一天 - x

Get first day of current week - x

我需要获取一周的第一天(星期一),从今天算起 8 周,其中 8 是一个变量。

在 PHP 中最好的方法是什么?

你可以用 PHP 中的日期做一些数学运算,比如:

$now = date('F d, Y H:i');
$newdate = date('F d, Y H:i', strtotime($now.' - 8 weeks'));
echo $newdate;

在这种情况下,它将输出当前日期减去 8 周。

还要计算今天是哪一天,您可以使用:

$dw = date( "w", strtotime($newdate));

其中 $dw 将为 0(星期日)到 6(星期六)更多信息可以找到:PHP: date

解决方案

在您的情况下,它将如下所示:

<?php
$weeks = 8;

$now = date('F d, Y H:i:s');
$newdate = date('F d, Y H:i:s', strtotime($now.' - '.$weeks.' weeks'));
$new_date_day = date( "w", strtotime($newdate));
$minus = $new_date_day - 1;

if ($minus < 0) { //check if sunday
    $plus = $minus * -1;
    $newdate = date('F d, Y H:i:s', strtotime($newdate.' + '.$plus.' days'));
} else {    
    $newdate = date('F d, Y H:i:s', strtotime($newdate.' - '.$minus.' days'));
}

echo $newdate;
?>

当然你可以echo任何你想要的约会方式。 F.ex。 F d, Y H:i:s 将输出 November 28, 2016 06:18:03.

$weeks = 8;

// Timestamp for $weeks weeks ago
$time = strtotime("$weeks weeks ago");

// Day of the week for $time (1 - Mon, ...)
$week_day = date('N', $time);

// Number of days from Monday
$diff = $week_day - 1;

// The date of the Monday $weeks weeks ago
echo date('j', $time - ($diff * 24 * 3600));

其实并不复杂,你所要做的就是稍微玩一下日期时间;

<?php
$dt = new Datetime(sprintf('%d weeks ago', 8)); // replace 8 with variable, your value, whatever
$day = $dt->format('w');
$dt->modify(sprintf('%d days go', ($day - 1) % 7));

您的 $dt 应该具有您寻求的价值

你可以这样做

echo date("l M-d-Y", strtotime('monday this week'));
echo date("l M-d-Y", strtotime('sunday this week'));
echo date("l M-d-Y", strtotime('monday last week'));
echo date("l M-d-Y", strtotime('sunday last week'));
echo date("l M-d-Y", strtotime('monday next week'));
echo date("l M-d-Y", strtotime('sunday next week'));

您也可以按月搜索

echo date("l M-d-Y", strtotime('first day of this month'));
echo date("l M-d-Y", strtotime('last day of this month'));
echo date("l M-d-Y", strtotime('first day of last month'));
echo date("l M-d-Y", strtotime('last day of last month'));
echo date("l M-d-Y", strtotime('first day of next month'));
echo date("l M-d-Y", strtotime('last day of next month'));