获取本周的第一天 - x

时间:2016-11-29 10:49:19

标签: php date datetime strtotime mktime

我需要得到一周的第一天(星期一),从今天开始的8周,其中8是变量。

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

4 个答案:

答案 0 :(得分:0)

您可以使用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

答案 1 :(得分:0)

$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));

答案 2 :(得分:0)

实际上并不是真的很复杂,你所要做的就是用日期时间来玩一点;

<?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应该具有您寻求的价值

答案 3 :(得分:0)

你可以这样做

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'));