在 PHP 中获取给定周的开始和结束天数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/923925/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:20:38  来源:igfitidea点击:

Get Start and End Days for a Given Week in PHP

phpdatetime

提问by Zahymaka

I'm trying to get the week range using Sunday as the start date, and a reference date, say $date, but I just can't seem to figure it out.

我正在尝试使用星期日作为开始日期和参考日期来获取周范围,例如$date,但我似乎无法弄清楚。

For example, if I had $date as 2009-05-01, I would get 2009-04-26 and 2009-05-02. 2009-05-10 would yield 2009-05-10 and 2009-05-16. My current code looks like this (I can't remember where I lifted it from, as I forgot to put down the url in my comments):

例如,如果 $date 为 2009-05-01,我将得到 2009-04-26 和 2009-05-02。2009-05-10 将产生 2009-05-10 和 2009-05-16。我当前的代码看起来像这样(我不记得我从哪里提取的,因为我忘记在评论中写下网址):

function x_week_range(&$start_date, &$end_date, $date)
{
    $start_date = '';
    $end_date = '';
    $week = date('W', strtotime($date));
    $week = $week;

    $start_date = $date;

    $i = 0;
    while(date('W', strtotime("-$i day")) >= $week) {
        $start_date = date('Y-m-d', strtotime("-$i day"));
        $i++;
    }

    list($yr, $mo, $da) = explode('-', $start_date);

    $end_date = date('Y-m-d', mktime(0, 0, 0, $mo, $da + 6, $yr));
}

I realized all it did was add 7 days to the current date. How would you do this?

我意识到它所做的只是将当前日期增加了 7 天。你会怎么做?

回答by Paolo Bergantino

I would take advantange of PHP's strtotimeawesomeness:

我会利用 PHP 的strtotime 优势

function x_week_range(&$start_date, &$end_date, $date) {
    $ts = strtotime($date);
    $start = (date('w', $ts) == 0) ? $ts : strtotime('last sunday', $ts);
    $start_date = date('Y-m-d', $start);
    $end_date = date('Y-m-d', strtotime('next saturday', $start));
}

Tested on the data you provided and it works. I don't particularly like the whole reference thing you have going on, though. If this was my function, I'd have it be like this:

对您提供的数据进行了测试,并且可以正常工作。不过,我并不特别喜欢你所进行的整个参考。如果这是我的功能,我会是这样的:

function x_week_range($date) {
    $ts = strtotime($date);
    $start = (date('w', $ts) == 0) ? $ts : strtotime('last sunday', $ts);
    return array(date('Y-m-d', $start),
                 date('Y-m-d', strtotime('next saturday', $start)));
}

And call it like this:

并这样称呼它:

list($start_date, $end_date) = x_week_range('2009-05-10');

I'm not a big fan of doing math for things like this. Dates are tricky and I prefer to have PHP figure it out.

我不喜欢为这样的事情做数学。日期很棘手,我更喜欢让 PHP 弄清楚。

回答by jjwdesign

To everyone still using mktime(), strtotime() and other PHP functions... give the PHP5 DateTimeClass a try. I was hesitant at first, but it's really easy to use. Don't forget about using clone() to copy your objects.

对于仍在使用 mktime()、strtotime() 和其他 PHP 函数的每个人...试试PHP5 DateTime类。起初我很犹豫,但它真的很容易使用。不要忘记使用 clone() 来复制您的对象。

Edit: This code was recently edited to handle the case where the current day is Sunday. In that case, we have to get the past Saturday and then add one day to get Sunday.

编辑:此代码最近被编辑以处理当前日期是星期日的情况。在这种情况下,我们必须得到过去的星期六,然后再加一天得到星期日。

$dt_min = new DateTime("last saturday"); // Edit
$dt_min->modify('+1 day'); // Edit
$dt_max = clone($dt_min);
$dt_max->modify('+6 days');

Then format as you need it.

然后根据需要格式化。

echo 'This Week ('.$dt_min->format('m/d/Y').'-'.$dt_max->format('m/d/Y').')';

Make sure to set your timezone early in your code.

确保在代码中尽早设置时区。

date_default_timezone_set('America/New_York');

回答by Crazy Joe Malloy

Apparently 'w' formatting value of date() or the format method of a DateTime object will return the day of the week as a number (by default, 0=Sunday, 1=Monday, etc)

显然 date() 的 'w' 格式值或 DateTime 对象的格式方法将返回星期几作为数字(默认情况下,0=星期日,1=星期一等)

You could take this and subtract it's value as days from the current day to find the beginning of the week.

你可以把它从当前天减去它的值,以找到一周的开始。

$start_date = new DateTime("2009-05-13");
$day_of_week = $start_date->format("w");

$start_date->modify("-$day_of_week day");

$start_date will now be equal to the Sunday of that week, from there you can add 7 days to get the end of the week or what-have-you.

$start_date 现在将等于那一周的星期日,从那里你可以添加 7 天来获得一周的结束或你有什么。

回答by David Bélanger

Base on @jjwdesign's answer, I developed a function that can calculate the beginning and ending of a week for a specific date using the DateTime class. WILL WORK ON PHP 5.3.0++

基于@jjwdesign 的回答,我开发了一个函数,可以使用 DateTime 类计算特定日期的一周的开始和结束。将适用于 PHP 5.3.0++

The difference is you can set the day you want as the "beginning" between 0 (monday) and 6 (sunday).

不同之处在于您可以将所需的日期设置为 0(星期一)和 6(星期日)之间的“开始”。

Here's the function :

这是功能:

if(function_exists('grk_Week_Range') === FALSE){
    function grk_Week_Range($DateString, $FirstDay=6){
        #   Valeur par défaut si vide
        if(empty($DateString) === TRUE){
            $DateString = date('Y-m-d');
        }

        #   On va aller chercher le premier jour de la semaine qu'on veut
        $Days = array(
            0 => 'monday',
            1 => 'tuesday',
            2 => 'wednesday',
            3 => 'thursday',
            4 => 'friday',
            5 => 'saturday',
            6 => 'sunday'
        );

        #   On va définir pour de bon le premier jour de la semaine     
        $DT_Min = new DateTime('last '.(isset($Days[$FirstDay]) === TRUE ? $Days[$FirstDay] : $Days[6]).' '.$DateString);
        $DT_Max = clone($DT_Min);

        #   On renvoie les données
        return array(
            $DT_Min->format('Y-m-d'),
            $DT_Max->modify('+6 days')->format('Y-m-d')
        );
    }
}

Results :

结果 :

print_r(grk_Week_Range('2013-08-11 16:45:32', 0));
print_r(grk_Week_Range('2013-08-11 16:45:32', 1));
print_r(grk_Week_Range('2013-08-11 16:45:32', 2));
print_r(grk_Week_Range('2013-08-11 16:45:32', 3));
print_r(grk_Week_Range('2013-08-11 16:45:32', 4));
print_r(grk_Week_Range('2013-08-11 16:45:32', 5));
print_r(grk_Week_Range('2013-08-11 16:45:32', 6));

Array
(
    [0] => 2013-07-29
    [1] => 2013-08-04
)
Array
(
    [0] => 2013-07-30
    [1] => 2013-08-05
)
Array
(
    [0] => 2013-07-31
    [1] => 2013-08-06
)
Array
(
    [0] => 2013-07-25
    [1] => 2013-07-31
)
Array
(
    [0] => 2013-07-26
    [1] => 2013-08-01
)
Array
(
    [0] => 2013-07-27
    [1] => 2013-08-02
)
Array
(
    [0] => 2013-07-28
    [1] => 2013-08-03
)

回答by Rob

Here's my version, which uses a similar notion to Clay's:

这是我的版本,它使用与 Clay 类似的概念:

/**
 * Start of the week
 *
 * 0 = Sun, 1 = Mon, etc.
 */
define( 'WEEK_START', 0 );

/**
 * Determine the start and end dates for
 * the week in which the specified date
 * falls
 *
 * @param $date Date in week
 * @param $start Week start (out)
 * @param $end Week end (out)
 */
function week_bounds( $date, &$start, &$end ) {
    $date = strtotime( $date );
    // Find the start of the week, working backwards
    $start = $date;
    while( date( 'w', $start ) > WEEK_START ) {
        $start -= 86400; // One day
    }
    // End of the week is simply 6 days from the start
    $end = date( 'Y-m-d', $start + ( 6 * 86400 ) );
    $start = date( 'Y-m-d', $start );
}

Lightly tested. Code may not be bulletproof, or handle dates in the far past or future. Use at your own risk. Do not immerse the code in water. Do not show the code to those of a nervous disposition, or with a hatred of the dollar sign. Not tested on animals. Safe for use by vegetarians. Author warrants that the code will never, ever speak to you. In the unlikely event that the code does try to engage you in conversation, the author advises you to disregard any and all advice it gives.

轻度测试。代码可能不是防弹的,或者处理过去或未来的日期。使用风险自负。请勿将代码浸入水中。不要向那些神经质或憎恨美元符号的人展示代码。未在动物身上进行测试。素食者可安全使用。作者保证代码永远不会对你说话。万一代码确实试图让您参与对话,作者建议您忽略它提供的任何和所有建议。

回答by coredumperror

In trying to find a more streamlined version of the accepted answer by Paolo Bergantino, I discovered a really nice way to get this done:

在试图找到 Paolo Bergantino 接受的答案的更简化版本时,我发现了一种非常好的方法来完成这项工作:

function x_week_range2($date) {
  $ts = strtotime($date);
  $start = strtotime('sunday this week -1 week', $ts);
  $end = strtotime('sunday this week', $ts);
  return array(date('Y-m-d', $start), date('Y-m-d', $end));
}

The 'sunday this week' string always means "The Sunday at the endof this week." If used on a timestamp that falls on a Sunday, it will be the following Sunday. This lets you avoid the need for the ternary operator in Paola's solution.

'sunday this week' 字符串始终表示“本周结束时的星期日”。如果用于星期日的时间戳,则为下一个星期日。这让您无需在 Paola 的解决方案中使用三元运算符。

回答by Vinit Kadkol

Use this to get the "week" number from any given date.

使用它来获取任何给定日期的“周”数。

//October 29, 2009 is my birthday
echo $week date('W', strtotime('2009-10-29'));
//OUTPUT: 44
//October 29 is the 44th week in the year 2009

Now pass the parameters for getWeekDates function as "year (2009)" and "$week".

现在将 getWeekDates 函数的参数作为“year (2009)”和“$week”传递。

function getWeekDates($year, $week, $start=true){
        $from = date("Y-m-d", strtotime("{$year}-W{$week}-1")); //Returns the date of monday in week
        $to = date("Y-m-d", strtotime("{$year}-W{$week}-7"));   //Returns the date of sunday in week

        if($start) {
            return $from;
        } else {
            return $to;
        }
        //return "Week {$week} in {$year} is from {$from} to {$to}.";
    }

For More Info Please refer this link http://blog.ekini.net/2009/07/09/php-get-start-and-end-dates-of-a-week-from-datew/

有关更多信息,请参阅此链接 http://blog.ekini.net/2009/07/09/php-get-start-and-end-dates-of-a-week-from-datew/

回答by Waqas

You can now use DateTime to get start/end dates of week(s)

您现在可以使用 DateTime 获取周的开始/结束日期

function getDateRangeForAllWeeks($start, $end){
    $fweek = getDateRangeForWeek($start);
    $lweek = getDateRangeForWeek($end);
    $week_dates = [];
    while($fweek['sunday']!=$lweek['sunday']){
        $week_dates [] = $fweek;
        $date = new DateTime($fweek['sunday']);
        $date->modify('next day');

        $fweek = getDateRangeForWeek($date->format("Y-m-d"));
    }
    $week_dates [] = $lweek;

    return $week_dates;
}

function getDateRangeForWeek($date){
    $dateTime = new DateTime($date);
    $monday = clone $dateTime->modify(('Sunday' == $dateTime->format('l')) ? 'Monday last week' : 'Monday this week');
    $sunday = clone $dateTime->modify('Sunday this week'); 
    return ['monday'=>$monday->format("Y-m-d"), 'sunday'=>$sunday->format("Y-m-d")];
}

Usage

用法

print_r( getDateRangeForWeek("2016-05-07") );

print_r( getDateRangeForAllWeeks("2015-11-07", "2016-02-15") );

回答by Pramod Amrutkar

A simple code to return the days from start DateTime and end DateTime. Using gmdate() method you can format date/time.

一个简单的代码,用于返回从开始日期时间到结束日期时间的天数。使用 gmdate() 方法可以格式化日期/时间。

$start_str_date = strtotime($start_date);
$end_str_date = strtotime($end_date);
$interval_days = $end_str_date - $start_str_date;
$days = gmdate('d',$interval_days);
echo $days;