简体   繁体   English

获取当前星期的第一天-x

[英]Get first day of current week - x

I need to get the first day of the week (Monday), 8 weeks back from today, where 8 is a variable. 我需要从今天起8周返回星期的第一天(星期一),其中8是变量。

What's the best way to do that in PHP? 用PHP做到这一点的最佳方法是什么?

You can make some math with dates in PHP like: 您可以使用PHP中的日期进行一些数学运算,例如:

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

In this case it will output a current date minus 8 weeks. 在这种情况下,它将输出当前日期减去8周。

Also to count which day is today you can use: 要计算今天是哪一天,您可以使用:

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

Where $dw will be 0 (for Sunday) through 6 (for Saturday) more informations can be found: PHP: date 其中$dw为0(星期日)至6(星期六),可以找到更多信息: PHP:date

Solution

In your case it would look as follows: 您的情况如下所示:

<?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;
?>

Of course you can echo what ever style of date you want. 当然,您可以echo您想要的日期样式。 F.ex. F.ex. F d, YH:i:s will output November 28, 2016 06:18:03 . F d, YH: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));

It's not really complicated actually, all you got to do is play a little bit with datetimes ; 实际上,这并不复杂,您所要做的就是稍微玩一些日期时间;

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

your $dt should then have the value you seek 那么您的$dt应该具有您想要的价值

You can do this way 你可以这样

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

You can also search monthwise 您也可以按月搜索

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM