简体   繁体   English

在 PHP 中获取一周的第一天?

[英]Get first day of week in PHP?

Given a date MM-dd-yyyy format, can someone help me get the first day of the week?给定日期MM-dd-yyyy格式,有人可以帮我得到一周的第一天吗?

Here is what I am using...这是我正在使用的...

$day = date('w');
$week_start = date('m-d-Y', strtotime('-'.$day.' days'));
$week_end = date('m-d-Y', strtotime('+'.(6-$day).' days'));

$day contains a number from 0 to 6 representing the day of the week (Sunday = 0, Monday = 1, etc.). $day包含一个从 0 到 6 的数字,表示星期几(星期日 = 0,星期一 = 1 等)。
$week_start contains the date for Sunday of the current week as mm-dd-yyyy. $week_start包含当前周星期日的日期为 mm-dd-yyyy。
$week_end contains the date for the Saturday of the current week as mm-dd-yyyy. $week_end包含当前周星期六的日期,如 mm-dd-yyyy。

Very simple to use strtotime function :使用strtotime函数非常简单:

echo date("Y-m-d", strtotime('monday this week')), "\n";   

echo date("Y-m-d", strtotime('sunday this week')), "\n";

It differs a bit across PHP versions :在 PHP 版本之间略有不同

Output for 5.3.0 - 5.6.6, php7@20140507 - 20150301, hhvm-3.3.1 - 3.5.1 5.3.0 - 5.6.6、php7@20140507 - 20150301、hhvm-3.3.1 - 3.5.1 的输出

2015-03-16
2015-03-22

Output for 4.3.5 - 5.2.17 4.3.5 - 5.2.17 的输出

2015-03-23
2015-03-22

Output for 4.3.0 - 4.3.4 4.3.0 - 4.3.4 的输出

2015-03-30
2015-03-29

Comparing at Edge-Cases比较边缘情况

Relative descriptions like this week have their own context.本周这样的相关描述有其自身的背景。 The following shows the output for this week monday and sunday when it's a monday or a sunday:以下显示了本周星期一和星期日的输出,当它是星期一或星期日时:

$date = '2015-03-16'; // monday
echo date("Y-m-d", strtotime('monday this week', strtotime($date))), "\n";   
echo date("Y-m-d", strtotime('sunday this week', strtotime($date))), "\n";

$date = '2015-03-22'; // sunday
echo date("Y-m-d", strtotime('monday this week', strtotime($date))), "\n";   
echo date("Y-m-d", strtotime('sunday this week', strtotime($date))), "\n";

Againt it differs a bit across PHP versions :同样,它在 PHP 版本中略有不同:

Output for 5.3.0 - 5.6.6, php7@20140507 - 20150301, hhvm-3.3.1 - 3.5.1 5.3.0 - 5.6.6、php7@20140507 - 20150301、hhvm-3.3.1 - 3.5.1 的输出

2015-03-16
2015-03-22
2015-03-23
2015-03-29

Output for 4.3.5 - 5.0.5, 5.2.0 - 5.2.17 4.3.5 - 5.0.5、5.2.0 - 5.2.17 的输出

2015-03-16
2015-03-22
2015-03-23
2015-03-22

Output for 5.1.0 - 5.1.6 5.1.0 - 5.1.6 的输出

2015-03-23
2015-03-22
2015-03-23
2015-03-29

Output for 4.3.0 - 4.3.4 4.3.0 - 4.3.4 的输出

2015-03-23
2015-03-29
2015-03-30
2015-03-29
strtotime('this week', time());

Replace time().替换时间()。 Next sunday/last monday methods won't work when the current day is sunday/monday.当前日是星期日/星期一时,下一个星期日/上一个星期一的方法将不起作用。

Keep it simple :把事情简单化 :

<?php    
$dateTime = new \DateTime('2020-04-01');
$monday = clone $dateTime->modify(('Sunday' == $dateTime->format('l')) ? 'Monday last week' : 'Monday this week');
$sunday = clone $dateTime->modify('Sunday this week');    
?>

Source : PHP manual来源: PHP 手册

NB: as some user commented the $dateTime value will be modified.注意:正如一些用户评论的那样, $dateTime 值将被修改。

$givenday = date("w", mktime(0, 0, 0, MM, dd, yyyy));

This gives you the day of the week of the given date itself where 0 = Sunday and 6 = Saturday.这为您提供给定日期本身的星期几,其中0 = 星期日和6 = 星期六。 From there you can simply calculate backwards to the day you want.从那里你可以简单地向后计算你想要的那一天。

This question needs a good DateTime answer:-这个问题需要一个很好的DateTime答案:-

function firstDayOfWeek($date)
{
    $day = DateTime::createFromFormat('m-d-Y', $date);
    $day->setISODate((int)$day->format('o'), (int)$day->format('W'), 1);
    return $day->format('m-d-Y');
}

var_dump(firstDayOfWeek('06-13-2013'));

Output:-输出:-

string '06-10-2013' (length=10)

This will deal with year boundaries and leap years.这将处理年份边界和闰年。

EDIT: the below link is no longer running on the version of PHP stated.编辑:以下链接不再在声明的 PHP 版本上运行。 It is running on PHP 5.6 which improves the reliability of strtotime, but isn't perfect!它在 PHP 5.6 上运行,提高了 strtotime 的可靠性,但并不完美! The results in the table are live results from PHP 5.6.表中的结果是 PHP 5.6 的实时结果。

For what it's worth, here is a breakdown of the wonky behavior of strtotime when determining a consistent frame of reference:对于它的价值,这里是在确定一致的参考框架时 strtotime 不稳定行为的细分:

http://gamereplays.org/reference/strtotime.php http://gamereplays.org/reference/strtotime.php

Basically only these strings will reliably give you the same date, no matter what day of the week you're currently on when you call them:基本上只有这些字符串才能可靠地为您提供相同的日期,无论您在调用它们时当前处于一周中的哪一天:

strtotime("next monday");
strtotime("this sunday");
strtotime("last sunday"); 

The following code should work with any custom date, just uses the desired date format.以下代码适用于任何自定义日期,只需使用所需的日期格式。

$custom_date = strtotime( date('d-m-Y', strtotime('31-07-2012')) ); 
$week_start = date('d-m-Y', strtotime('this week last monday', $custom_date));
$week_end = date('d-m-Y', strtotime('this week next sunday', $custom_date));
echo '<br>Start: '. $week_start;
echo '<br>End: '. $week_end;

I tested the code with PHP 5.2.17 Results:我用 PHP 5.2.17 结果测试了代码:

Start: 30-07-2012
End: 05-08-2012

假设星期一为一周的第一天,这有效:

echo date("M-d-y", strtotime('last monday', strtotime('next week', time())));

How about this?这个怎么样?

$first_day_of_week = date('m-d-Y', strtotime('Last Monday', time()));
$last_day_of_week = date('m-d-Y', strtotime('Next Sunday', time()));

This is what I am using to get the first and last day of the week from any date .这是我用来从任何日期获取一周的第一天和最后一天的方法。 In this case, monday is the first day of the week...在这种情况下,星期一是一周的第一天......

$date = date('Y-m-d') // you can put any date you want
$nbDay = date('N', strtotime($date));
$monday = new DateTime($date);
$sunday = new DateTime($date);
$monday->modify('-'.($nbDay-1).' days');
$sunday->modify('+'.(7-$nbDay).' days');

Here I am considering Sunday as first & Saturday as last day of the week.在这里,我将周日作为第一天,周六作为一周的最后一天。

$m = strtotime('06-08-2012');  
$today =   date('l', $m);  
$custom_date = strtotime( date('d-m-Y', $m) );   
if ($today == 'Sunday') {  
   $week_start = date("d-m-Y", $m);  
} else {  
  $week_start = date('d-m-Y', strtotime('this week last sunday', $custom_date));  
}  

if ($today == 'Saturday') {  
  $week_end = date("d-m-Y", $m);
} else {  
  $week_end = date('d-m-Y', strtotime('this week next saturday', $custom_date));  
}
echo '<br>Start: '. $week_start;  
echo '<br>End: '. $week_end;  

Output :输出 :

Start: 05-08-2012开始: 05-08-2012
End: 11-08-2012结束: 11-08-2012

只需使用date($format, strtotime($date,' LAST SUNDAY + 1 DAY'));

How about this?这个怎么样?

$day_of_week = date('N', strtotime($string_date));
$week_first_day = date('Y-m-d', strtotime($string_date . " - " . ($day_of_week - 1) . " days"));
$week_last_day = date('Y-m-d', strtotime($string_date . " + " . (7 - $day_of_week) . " days"));

Try this:尝试这个:

function week_start_date($wk_num, $yr, $first = 1, $format = 'F d, Y')
{
    $wk_ts  = strtotime('+' . $wk_num . ' weeks', strtotime($yr . '0101'));
    $mon_ts = strtotime('-' . date('w', $wk_ts) + $first . ' days', $wk_ts);
    return date($format, $mon_ts);
}

$sStartDate = week_start_date($week_number, $year);
$sEndDate   = date('F d, Y', strtotime('+6 days', strtotime($sStartDate)));

(from this forum thread ) (来自这个论坛帖子

This is the shortest and most readable solution I found:这是我发现的最短、最易读的解决方案:

    <?php
    $weekstart = strtotime('monday this week');
    $weekstop = strtotime('sunday this week 23:59:59');
    //echo date('d.m.Y H:i:s', $weekstart) .' - '. date('d.m.Y H:i:s', $weekstop);
    ?>

strtotime is faster than new DateTime()->getTimestamp() . strtotimenew DateTime()->getTimestamp()快。

$string_date = '2019-07-31';
echo $day_of_week = date('N', strtotime($string_date));
echo $week_first_day = date('Y-m-d', strtotime($string_date . " - " . ($day_of_week - 1) . " days"));
echo $week_last_day = date('Y-m-d', strtotime($string_date . " + " . (7 - $day_of_week) . " days"));

Given PHP version pre 5.3 following function gives you a first day of the week of given date (in this case - Sunday, 2013-02-03):鉴于 PHP 5.3 之前的版本,以下函数为您提供给定日期的一周的第一天(在本例中 - 星期日,2013-02-03):

<?php
  function startOfWeek($aDate){
    $d=strtotime($aDate);
    return strtotime(date('Y-m-d',$d).' - '.date("w",$d).' days');
  }

  echo(date('Y-m-d',startOfWeek("2013-02-07")).'
');
?>
$today_day = date('D'); //Or add your own date
$start_of_week = date('Ymd');
$end_of_week = date('Ymd');

if($today_day != "Mon")
    $start_of_week = date('Ymd', strtotime("last monday"));

if($today_day != "Sun")
                    $end_of_week = date('Ymd', strtotime("next sunday"));
$monday = date('d-m-Y',strtotime('last monday',strtotime('next monday',strtotime($date))));

You have to get next monday first then get the 'last monday' of next monday.您必须先获得下周一,然后才能获得下周一的“最后一个周一”。 So if the given date is monday it will return the same date not last week monday.因此,如果给定的日期是星期一,它将返回相同的日期而不是上周的星期一。

If you want Monday as the start of your week, do this:如果您希望星期一作为一周的开始,请执行以下操作:

$date = '2015-10-12';
$day = date('N', strtotime($date));
$week_start = date('Y-m-d', strtotime('-'.($day-1).' days', strtotime($date)));
$week_end = date('Y-m-d', strtotime('+'.(7-$day).' days', strtotime($date)));

A smart way of doing this is to let PHP handle timezone differences and Daylight Savings Time (DST).一个聪明的方法是让 PHP 处理时区差异和夏令时 (DST)。 Let me show you how to do this.让我告诉你如何做到这一点。

This function will generate all days from Monday until Friday, inclusive (handy for generating work week days):此函数将生成从星期一到星期五的所有日子,包括在内(生成工作日很方便):

class DateTimeUtilities {
    public static function getPeriodFromMondayUntilFriday($offset = 'now') {
        $now = new \DateTimeImmutable($offset, new \DateTimeZone('UTC'));
        $today = $now->setTime(0, 0, 1);

        $daysFromMonday = $today->format('N') - 1;

        $monday = $today->sub(new \DateInterval(sprintf('P%dD', $daysFromMonday)));
        $saturday = $monday->add(new \DateInterval('P5D'));

        return new \DatePeriod($monday, new \DateInterval('P1D'), $saturday);
    }
}

foreach (DateTimeUtilities::getPeriodFromMondayUntilFriday() as $day) {
    print $day->format('c');
    print PHP_EOL;
}

This will return datetimes Monday-Friday for current week.这将返回当前周周一至周五的日期时间。 To do the same for an arbitrary date, pass a date as a parameter to DateTimeUtilities ::getPeriodFromMondayUntilFriday , thus:要对任意日期执行相同操作,请将日期作为参数传递给DateTimeUtilities ::getPeriodFromMondayUntilFriday ,因此:

foreach (DateTimeUtilities::getPeriodFromMondayUntilFriday('2017-01-02T15:05:21+00:00') as $day) {
    print $day->format('c');
    print PHP_EOL;
}

//prints 
//2017-01-02T00:00:01+00:00
//2017-01-03T00:00:01+00:00
//2017-01-04T00:00:01+00:00
//2017-01-05T00:00:01+00:00
//2017-01-06T00:00:01+00:00

Only interested in Monday, as the OP asked?正如 OP 所问的那样,只对星期一感兴趣?

$monday = DateTimeUtilities::getPeriodFromMondayUntilFriday('2017-01-02T15:05:21+00:00')->getStartDate()->format('c');
print $monday;
// prints
//2017-01-02T00:00:01+00:00

您使用strptime()解析日期并在结果上使用date()

date('N', strptime('%m-%d-%g', $dateString));
<?php
/* PHP 5.3.0 */

date_default_timezone_set('America/Denver'); //Set apprpriate timezone
$start_date = strtotime('2009-12-15'); //Set start date

//Today's date if $start_date is a Sunday, otherwise date of previous Sunday
$today_or_previous_sunday = mktime(0, 0, 0, date('m', $start_date), date('d', $start_date), date('Y', $start_date)) - ((date("w", $start_date) ==0) ? 0 : (86400 * date("w", $start_date)));

//prints 12-13-2009 (month-day-year)
echo date('m-d-Y', $today_or_previous_sunday);

?>

(Note: MM, dd and yyyy in the Question are not standard php date format syntax - I can't be sure what is meant, so I set the $start_date with ISO year-month-day) (注意:问题中的 MM、dd 和 yyyy 不是标准的 php 日期格式语法 - 我不确定是什么意思,所以我将 $start_date 设置为 ISO 年月日)

Another way to do it....另一种方法来做到这一点......

$year = '2014';
$month = '02';
$day = '26';

$date = DateTime::createFromFormat('Y-m-d H:i:s', $year . '-' . $month . '-' . $day . '00:00:00');
$day = date('w', $date->getTimestamp());

// 0=Sunday 6=Saturday
if($day!=0){

   $newdate = $date->getTimestamp() - $day * 86400;  //86400 seconds in a day

   // Look for DST change 
   if($old = date('I', $date->getTimestamp()) != $new = date('I', $newdate)){
       if($old == 0){
           $newdate -= 3600;  //3600 seconds in an hour
       } else {
           $newdate += 3600;
       }
   }

   $date->setTimestamp($newdate);
}

echo $date->format('D Y-m-d H:i:s');

The easiest way to get first day(Monday) of current week is:获取本周第一天(星期一)的最简单方法是:

strtotime("next Monday") - 604800;

where 604800 - is count of seconds in 1 week(60*60*24*7).其中 604800 - 是 1 周内的秒数(60*60*24*7)。

This code get next Monday and decrease it for 1 week.此代码下周一获取并减少 1 周。 This code will work well in any day of week.此代码在一周中的任何一天都可以正常工作。 Even if today is Monday.即使今天是星期一。

I found this quite frustrating given that my timezone is Australian and that strtotime() hates UK dates.鉴于我的时区是澳大利亚时区并且strtotime()讨厌英国日期,我发现这非常令人沮丧。

If the current day is a Sunday, then strtotime("monday this week") will return the day after.如果当天是星期日,则strtotime("monday this week")将在后一天返回。

To overcome this:为了克服这个:

Caution : This is only valid for Australian/UK dates注意:这仅适用于澳大利亚/英国日期

$startOfWeek = (date('l') == 'Monday') ? date('d/m/Y 00:00') : date('d/m/Y', strtotime("last monday 00:00"));
$endOfWeek = (date('l') == 'Sunday') ? date('d/m/Y 23:59:59') : date('d/m/Y', strtotime("sunday 23:59:59"));

Here's a one liner for the first day of last week, and the last day of last week as a DateTime object.这是上周第一天和上周最后一天作为DateTime对象的单行。

$firstDay = (new \DateTime())->modify(sprintf('-%d day', date('w') + 7))
                             ->setTime(0, 0, 0);
$lastDay = (new \DateTime())->modify(sprintf('-%d day', date('w') + 1))
                            ->setTime(23, 59, 59);

I've come against this question a few times and always surprised the date functions don't make this easier or clearer.我已经多次遇到这个问题,并且总是惊讶于日期函数并没有使这更容易或更清晰。 Here's my solution for PHP5 that uses the DateTime class:这是我使用DateTime类的 PHP5 解决方案:

/**
 * @param DateTime $date A given date
 * @param int $firstDay 0-6, Sun-Sat respectively
 * @return DateTime
 */
function getFirstDayOfWeek(DateTime $date, $firstDay = 0) {
    $offset = 7 - $firstDay;
    $ret = clone $date;
    $ret->modify(-(($date->format('w') + $offset) % 7) . 'days');
    return $ret;
}

Necessary to clone to avoid altering the original date.需要克隆以避免更改原始日期。

What about:关于什么:

$date = "2013-03-18"; 
$searchRow = date("d.m.Y", strtotime('last monday',strtotime($date." + 1 day")));
echo "for date " .$date ." we get this monday: " ;echo $searchRow; echo '<br>';

Its not the best way but i tested and if i am in this week i get the correct monday, and if i am on a monday i will get that monday.这不是最好的方法,但我测试过,如果我在本周,我会得到正确的星期一,如果我在星期一,我会得到那个星期一。

I found this solution helpful.我发现这个解决方案很有帮助。 Just subtract if it isn't monday to get the previous Monday.如果不是星期一,就减去上一个星期一。 I am using $lower_date as the date I pulled from a query that I then need to reconcile to the previous Monday.我使用 $lower_date 作为我从查询中提取的日期,然后我需要将其与上一个星期一进行协调。

//set this up to go backwards until you find monday
while(date('D',strtotime($lower_date))!='Mon'){
    $lower_date = date('Y-m-d', strtotime($lower_date . ' - 1 day')); //increase the upper spec
}

this one is prepared for today is monday这个准备今天是星期一

function lastMonday(\DateTime $date) {

    $timestamp = $date->getTimestamp();

    $monday = ( 1 == date( 'N', $timestamp ));

    if ($monday) {
        return $timestamp;
    } else {
        return strtotime( 'last monday', $timestamp );
    }
}

if you want it to get timestamp instead of DateTime change first two lines (get rid of date->getTimestamp) change them to just this如果您希望它获取时间戳而不是 DateTime,请更改前两行(去掉 date->getTimestamp)将它们更改为此

function lastMonday($timestamp) {

and if you want it to input string change first two lines to this如果你想让它输入字符串,请将前两行更改为此

function lastMonday($dateString) {

    $timestamp = strtotime($dateString);

I was searching for a solution similar to this and I finally came up with something that will return each day of the current week.我正在寻找与此类似的解决方案,我终于想出了一些可以在当前一周的每一天返回的东西。

//set current timestamp
$today = time();
//calculate the number of days since Monday
$dow = date('w', $today);
  $offset = $dow - 1;
if ($offset < 0) {
  $offset = 6;
  }
//calculate timestamp for Monday and Sunday
$monday = $today - ($offset * 86400);
$tuesday = $monday + (1 * 86400);
$wednesday = $monday + (2 * 86400);
$thursday = $monday + (3 * 86400);
$friday = $monday + (4 * 86400);
$saturday = $monday + (5 * 86400);
$sunday = $monday + (6 * 86400);
//print dates for Monday and Sunday in the current week
print date("Y-m-d", $monday) . "\n";
print date("Y-m-d", $tuesday) . "\n";
print date("Y-m-d", $wednesday) . "\n";
print date("Y-m-d", $thursday) . "\n";
print date("Y-m-d", $friday) . "\n";
print date("Y-m-d", $saturday) . "\n";
print date("Y-m-d", $sunday) . "\n";

Thank you to dbunic who posted this here: http://www.redips.net/php/week-list-current-date/#comments感谢 dbunic 在此处发布此内容: http : //www.redips.net/php/week-list-current-date/#comments

I use it:我用它:

$firstDate = date( 'Y-m-d', strtotime( 'Last Monday', strtotime('-1 week') ));
$lastDate = date( 'Y-m-d', strtotime( 'First Sunday', strtotime('-1 week') ));

Hope this help you!希望这对你有帮助!

You can use Carbon library as well您也可以使用 Carbon 库

$dateString = '02-21-2015'; // example in format MM-dd-yyyy
$date = Carbon::createFromFormat('m-d-Y', $dateString);
$date->hour(0)->minute(0)->second(0)->startOfWeek();
$dateString = $date->Format('m-d-Y'); // and you have got a string value "02-16-2015"

Should work:应该管用:

/**
 * Returns start of most recent Sunday.
 * 
 * @param null|int $timestamp
 * @return int
 */
public static function StartOfWeek($timestamp = null) {
    if($timestamp === null) $timestamp = time();
    $dow = idate('w', $timestamp); // Sunday = 0, Monday = 1, etc.
    return mktime(0, 0, 0, idate('m', $timestamp), idate('d', $timestamp) - $dow, idate('Y', $timestamp));
}

Input and output are unix timestamps.输入和输出是 unix 时间戳。 Use date to format.使用date进行格式化。

Just to note that timestamp math can also be a solution.请注意时间戳数学也可以是一种解决方案。 If you have in mind that 01.jan 1970 was a Thursday, then start of a week for any given date can be calculated with:如果您记得 1970 年 1 月 1 日是星期四,那么可以使用以下公式计算任何给定日期的一周开始时间:

function weekStart($dts)
{   return ($res=$dts-($dts+date('Z',$dts)+259200)%604800)
          +(date('I',$dts)-date('I',$res))*3600;
}

It is predictable for any timestamp and php version, using date-func ('Z', 'I') only for timezone and daylight-saving offsets.它对于任何时间戳和 php 版本都是可预测的,仅对时区和夏令时偏移量使用 date-func ('Z', 'I')。 And it produces same results as:它产生与以下相同的结果:

strtotime(date('Y-m-d', $dts).' - '.(date('N', $dts)-1.' days');

and with (the best and the most elegant) mentioned:并提到(最好和最优雅的):

strtotime('monday this week', $dts); 

In order to have the simplest code and have weeks starting on monday, I used this method:为了拥有最简单的代码并从星期一开始数周,我使用了这种方法:

$day = (date('w')+6)%7; //transform week start from sunday to monday
$time = strtotime('-'.$day.' days');

只是简单的在线回答;)

$mondayThisWeek = new Date($date . 'this week monday');

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

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