PHP获得一个月的周数

时间:2011-05-02 04:07:53

标签: php date

所以我有一个脚本可以返回特定月份和年份的周数。我如何从该月开始特定日期并确定它是否属于该月1,2,3,4或5周的一部分?

30 个答案:

答案 0 :(得分:45)

我曾经尝试过最令人沮丧的事情 - 但现在就是这样!

<?php

    /**
     * Returns the amount of weeks into the month a date is
     * @param $date a YYYY-MM-DD formatted date
     * @param $rollover The day on which the week rolls over
     */
    function getWeeks($date, $rollover)
    {
        $cut = substr($date, 0, 8);
        $daylen = 86400;

        $timestamp = strtotime($date);
        $first = strtotime($cut . "00");
        $elapsed = ($timestamp - $first) / $daylen;

        $weeks = 1;

        for ($i = 1; $i <= $elapsed; $i++)
        {
            $dayfind = $cut . (strlen($i) < 2 ? '0' . $i : $i);
            $daytimestamp = strtotime($dayfind);

            $day = strtolower(date("l", $daytimestamp));

            if($day == strtolower($rollover))  $weeks ++;
        }

        return $weeks;
    }


    //
    echo getWeeks("2011-06-11", "sunday"); //outputs 2, for the second week of the month
?>

答案 1 :(得分:25)

编辑:对“单行”这么多 - 需要的变量以避免使用条件重新计算。我在参加时默认参数。

function weekOfMonth($when = null) {
    if ($when === null) $when = time();
    $week = date('W', $when); // note that ISO weeks start on Monday
    $firstWeekOfMonth = date('W', strtotime(date('Y-m-01', $when)));
    return 1 + ($week < $firstWeekOfMonth ? $week : $week - $firstWeekOfMonth);
}

请注意,weekOfMonth(strtotime('Oct 31, 2011'));将返回6;与OP的预期相反,一些罕见的月份有6个星期。 2017年1月是另一个月,有6个ISO周 - 星期日,自从ISO星期一开始以来,第一个星期是去年的一周。

对于starshine531,要返回当月的0个索引周,请将return 1 +更改为return 0 +return (int)

对于Justin Stayton,从星期日而不是星期一开始的几周,我会使用strftime('%U'代替date('W',如下所示:

function weekOfMonth($when = null) {
    if ($when === null) $when = time();
    $week = strftime('%U', $when); // weeks start on Sunday
    $firstWeekOfMonth = strftime('%U', strtotime(date('Y-m-01', $when)));
    return 1 + ($week < $firstWeekOfMonth ? $week : $week - $firstWeekOfMonth);
}

对于这个版本,2017-04-30现在是4月的第6周,而2017-01-31现在是第5周。

答案 2 :(得分:13)

public function getWeeks($timestamp)
{
    $maxday    = date("t",$timestamp);
    $thismonth = getdate($timestamp);
    $timeStamp = mktime(0,0,0,$thismonth['mon'],1,$thismonth['year']);    //Create time stamp of the first day from the give date.
    $startday  = date('w',$timeStamp);    //get first day of the given month
    $day = $thismonth['mday'];
    $weeks = 0;
    $week_num = 0;

    for ($i=0; $i<($maxday+$startday); $i++) {
        if(($i % 7) == 0){
            $weeks++;
        }
        if($day == ($i - $startday + 1)){
            $week_num = $weeks;
        }
      }     
    return $week_num;
}

大家好,我一整天都在努力想出这个代码,我终于想通了,所以我想我会和大家分享。

您需要做的就是在功能中加上时间戳,它会将周数返回给您。

感谢

答案 3 :(得分:6)

此方法存在问题。如果通过日期(假设2012/01/01是星期日)和“$ rollover”日是“星期日”,那么这个函数将返回2.其中它实际上是第1周。我想我已经修复了以下功能。 请添加评论以使其更好。

function getWeeks($date, $rollover)
{
    $cut        = substr($date, 0, 8);
    $daylen     = 86400;
    $timestamp  = strtotime($date);
    $first      = strtotime($cut . "01");   
    $elapsed    = (($timestamp - $first) / $daylen)+1;
    $i          = 1;
    $weeks      = 0;
    for($i==1; $i<=$elapsed; $i++)
    {
        $dayfind        = $cut . (strlen($i) < 2 ? '0' . $i : $i);
        $daytimestamp   = strtotime($dayfind);
        $day            = strtolower(date("l", $daytimestamp));
        if($day == strtolower($rollover))
        {
            $weeks++;  
        }
    } 
    if($weeks==0)
    {
        $weeks++; 
    }
    return $weeks;  
}

答案 4 :(得分:5)

这是一个基于sberry数学解决方案的解决方案,但改为使用PHP DateTime类。

function week_of_month($date) {
    $first_of_month = new DateObject($date->format('Y/m/1'));
    $day_of_first = $first_of_month->format('N');
    $day_of_month = $date->format('j');
    return floor(($day_of_first + $day_of_month - 1) / 7) + 1;
}

答案 5 :(得分:4)

只需复制并过去代码并传递月份和年份。

例如month = 04 year = 2013。

这正是你所需要的。

$mm= $_REQUEST['month'];
$yy= $_REQUEST['year'];
$startdate=date($yy."-".$mm."-01") ;
$current_date=date('Y-m-t');
$ld= cal_days_in_month(CAL_GREGORIAN, $mm, $yy);
$lastday=$yy.'-'.$mm.'-'.$ld;
$start_date = date('Y-m-d', strtotime($startdate));
$end_date = date('Y-m-d', strtotime($lastday));
$end_date1 = date('Y-m-d', strtotime($lastday." + 6 days"));
$count_week=0;
$week_array = array();

for($date = $start_date; $date <= $end_date1; $date = date('Y-m-d', strtotime($date. ' + 7 days')))
{
    $getarray=getWeekDates($date, $start_date, $end_date);
echo "<br>";
$week_array[]=$getarray;
    echo "\n";
$count_week++;

}

// its give the number of week for the given month and year
echo $count_week;
//print_r($week_array);

function getWeekDates($date, $start_date, $end_date)
{
    $week =  date('W', strtotime($date));
    $year =  date('Y', strtotime($date));
    $from = date("Y-m-d", strtotime("{$year}-W{$week}+1"));
    if($from < $start_date) $from = $start_date;

    $to = date("Y-m-d", strtotime("{$year}-W{$week}-6")); 
    if($to > $end_date) $to = $end_date;

$array1 = array(
        "ssdate" => $from,
        "eedate" => $to,
);

return $array1;

   // echo "Start Date-->".$from."End Date -->".$to;
}

for($i=0;$i<$count_week;$i++)
{   
$start= $week_array[$i]['ssdate'];
echo "--";

$week_array[$i]['eedate'];
echo "<br>";
}

输出:

week( 0 )=>2013-03-01---2013-03-02

week( 1 )=>2013-03-03---2013-03-09

week( 2 )=>2013-03-10---2013-03-16

week( 3 )=>2013-03-17---2013-03-23

week( 4 )=>2013-03-24---2013-03-30

week( 5 )=>2013-03-31---2013-03-31

答案 6 :(得分:3)

这是我为满足我的要求所做的片段。希望这会对你有所帮助。

function getWeek($timestamp) {
 $week_year = date('W',$timestamp);
 $week = 0;//date('d',$timestamp)/7;
 $year = date('Y',$timestamp);
 $month = date('m',$timestamp);
 $day = date('d',$timestamp);
 $prev_month = date('m',$timestamp) -1;
if($month != 1 ){
    $last_day_prev = $year."-".$prev_month."-1";
    $last_day_prev = date('t',strtotime($last_day_prev));
    $week_year_last_mon = date('W',strtotime($year."-".$prev_month."-".$last_day_prev));
    $week_year_first_this = date('W',strtotime($year."-".$month."-1"));
    if($week_year_first_this == $week_year_last_mon){
        $week_diff = 0;
    }
    else{
        $week_diff = 1;
    }
    if($week_year ==1 && $month == 12 ){
    // to handle December's last two days coming in first week of January
        $week_year = 53;
    }
    $week = $week_year-$week_year_last_mon + 1 +$week_diff;
}
else{
 // to handle first three days January coming in last week of December.
    $week_year_first_this = date('W',strtotime($year."-01-1"));
    if($week_year_first_this ==52 || $week_year_first_this ==53){
        if($week_year == 52 || $week_year == 53){
            $week =1;
        }
        else{
            $week = $week_year + 1;
        }
    }
    else{
        $week = $week_year;
    }
}
return $week;

}

答案 7 :(得分:3)

对于周一至周日(ISO 8601)周(或者,如果您根本不在乎),您可以在一行中执行此操作:

function get_week_of_month($date) {
 return date('W', $date) - date('W', strtotime(date("Y-m-01", $date))) + 1;
}

Source

对于其他任何事情,(例如星期日至星期六),你只需在函数内调整$ date:

function get_week_of_month($date) {
 $date += 86400; //For weeks starting on Sunday
 return date('W', $date) - date('W', strtotime(date("Y-m-01", $date))) + 1;
}

Thanks to these guys/gals

注意:您可能会在年底遇到一些问题(例如,大约12 / 31,1 / 1等)。 Read more here.

答案 8 :(得分:2)

这是两个班轮:

function getWeekOfMonth(DateTime $date) {
    $firstDayOfMonth = new DateTime($date->format('Y-m-1'));

    return ceil(($firstDayOfMonth->format('N') + $date->format('j') - 1) / 7);
}

Wtower's solutions无法100%正常工作。

答案 9 :(得分:2)

我想我找到了一个优雅的解决方案

$time = time(); // or whenever
$week_of_the_month = ceil(date('d', $time)/7);

答案 10 :(得分:2)

这可能不是一个很好的方法,但这是我的第一个想法,我真的很累。

将所有日期放入数组中。日期对象必须具有日期名称(星期一)。创建一个搜索数组的方法,当你点击星期日时,你会在一个星期的计数器中加1。一旦找到您正在寻找的日期,请返回周计数器。这是一年中的一周。对于本月的一周,每次到达每个月的最后一天时,您都必须重置周计数器。

答案 11 :(得分:1)

我以为我也会分享我的功能。这将返回一个周数组。每周都是一个数组,以周日(0..6)作为关键,数月(1..31)为数值。

功能假设星期从星期日开始。

享受!

function get_weeks($year, $month){

    $days_in_month = date("t", mktime(0, 0, 0, $month, 1, $year));
    $weeks_in_month = 1;
    $weeks = array();

    //loop through month
    for ($day=1; $day<=$days_in_month; $day++) {

        $week_day = date("w", mktime(0, 0, 0, $month, $day, $year));//0..6 starting sunday

        $weeks[$weeks_in_month][$week_day] = $day;

        if ($week_day == 6) {
            $weeks_in_month++;
        }

    }

    return $weeks;

}

答案 12 :(得分:1)

我找到了一种简单的方法来确定今天的哪个星期,并且在任何其他日期都可以使用它。我在这里加上我的两分钱,因为我认为我的方式比列出的方法更紧凑。

$monthstart = date("N",strtotime(date("n/1/Y")));
$date =( date("j")+$monthstart ) /7;
$ddate= floor( $date );
if($ddate != date) {$ddate++;}

和$ ddate包含您可以修改它的周数

function findweek($indate)
{
  $monthstart = date("N",strtotime(date("n/1/Y",strtotime($indate))));
  $date =( date("j",strtotime($indate))+$monthstart ) /7;
  $ddate= floor( $date );
  if($ddate != $date) {$ddate++;}
  return $ddate;
}

它会返回你给它的任何日期的那个月的哪个星期。 它的作用是首先找到从一周开始到一个月的第一天的天数。然后将其添加到当前日期,然后将新日期除以7,这将为您提供自月初开始已过去的周数,包括已过去当前周的部分的小数位。所以我接下来要做的是将该数字向下舍入,然后将四舍五入的版本与原始版本进行比较,如果两者在一周结束时匹配,那么它已经在数字中。如果他们不这样做,那么只需在向下舍入的数字中添加一个,瞧你有当前的周数。

答案 13 :(得分:1)

我的5美分:

/**
* calculate number of weeks in a particular month
*/
function weeksInMonth($month=null,$year=null){

    if( null==($year) ) {
        $year =  date("Y",time());  
    }

    if(null==($month)) {
        $month = date("m",time());
    }

    // find number of days in this month
    $daysInMonths =  date('t',strtotime($year.'-'.$month.'-01'));

    $numOfweeks = ($daysInMonths%7==0?0:1) + intval($daysInMonths/7);

    $monthEndingDay= date('N',strtotime($year.'-'.$month.'-'.$daysInMonths));

    $monthStartDay = date('N',strtotime($year.'-'.$month.'-01'));

    if($monthEndingDay<$monthStartDay){

        $numOfweeks++;

    }

    return $numOfweeks;
}

答案 14 :(得分:1)

Srahul07的解决方案完美无缺...... 如果你遵守周一至周日周系统!在'murica,非商业人士往往周日至周六是一周,所以2011年5月1日是第1周和2011年5月2日仍然是第1周。

将以下逻辑添加到其函数的底部,在它返回$ week之前将其转换为星期日 - &gt;星期一系统:

if (!date('w',strtotime("$year-$month-01")) && date('w',$timestamp))
    $week--;
elseif (date('w',strtotime("$year-$month-01")) && !date('w',$timestamp))
    $week++;

答案 15 :(得分:1)

我创建了这个函数,来自巴西:)我希望它很有用

function weekofmonth($time) {

    $firstday       = 1;
    $lastday        = date('j',$time);
    $lastdayweek = 6; //Saturday

    $week = 1;
    for ($day=1;$day<=$lastday;$day++) {
        $timetmp = mktime(0, 0, 0, date('n',$time), $day, date('Y',$time));
        if (date('N',$timetmp) == $lastdayweek) {
            $week++;
        }
    }
    if (date('N',$time)==$lastdayweek) {
        $week--;
    }

    return $week;
}

$time = mktime(0, 0, 0, 9, 30, 2014);
echo weekofmonth($time);

答案 16 :(得分:0)

如果您明确希望将一个月分为4个星期,则可以使用此功能。 如果您想要

,这将很有帮助
  • “每月的第一个星期一”
  • “每月的第三个星期四”等。

我们在这里

/**
* This Calculates (and returns) the week number within a month, based on date('j') day of month.
* This is useful, if you want to have (for instance) the first Thu in month, regardless of date
* @param $Timestamp
* @return float|int
*/
function getWeekOfMonth($Timestamp)
{
    $DayOfMonth=date('j', $Timestamp); // Day of the month without leading zeros 0-31

    if($DayOfMonth>21) return 4;
    if($DayOfMonth>14) return 3;
    if($DayOfMonth>7) return 2;
    return 1;
}

答案 17 :(得分:0)

使用碳:

  

$ date = Carbon :: now();   $ d1 = $ date-&gt; startOfMonth();   $ d2 = $ date-&gt; endOfMonth();

     

$ weeks = $ d1-&gt; diffInWeeks($ d2);

答案 18 :(得分:0)

/**
         * In case of Week we can get the week of year. So whenever we will get the week of the month then we have to
         * subtract the until last month weeks from it will give us the current month week.
         */
        $dateComponents = getdate();

        if($dateComponents['mon'] == 1)
            $weekOfMonth = date('W', strtotime($dateComponents['year'].'-'.$dateComponents['mon'].'-'.$dateComponents['mday']))-1; // We subtract -1 to map it to the array
        else
            $weekOfMonth = date('W', strtotime($dateComponents['year'].'-'.$dateComponents['mon'].'-'.$dateComponents['mday']))-date('W', strtotime($dateComponents['year'].'-'.$dateComponents['mon'].'-01'));

答案 19 :(得分:0)

function getWeekOfMonth(\DateTime $date)
{
    $firstWeekdayOfMonth = new DateTime("first weekday 0 {$date->format('M')} {$date->format('Y')}");
    $offset = $firstWeekdayOfMonth->format('N')-1;
    return intval(($date->format('j') + $offset)/7)+1;
}

答案 20 :(得分:0)

如果我理解正确,那么问题是如何识别特定日期的一个月内的周数...我正在寻找类似的解决方案。我使用了上述答案的一些想法来开发我自己的解决方案。希望它对某人有所帮助。如果是,那么UpVote我的答案。

function week_number_within_month($datenew){

        $year =  date("Y",strtotime($datenew));  
        $month = date("m",strtotime($datenew));

    // find number of days in this month
    $daysInMonths =  date('t',strtotime($year.'-'.$month.'-01'));
    $numOfweeks = ($daysInMonths%7==0?0:1) + intval($daysInMonths/7);
    $monthEndingDay= date('N',strtotime($year.'-'.$month.'-'.$daysInMonths));
    $monthStartDay = date('N',strtotime($year.'-'.$month.'-01'));
    if($monthEndingDay<$monthStartDay){
        $numOfweeks++;
    }
    $date=date('Y/m/d', strtotime($year.'-'. $month.'-01'));
    $week_array=Array();
    for ($i=1; $i<=$numOfweeks; $i++){   /// create an Array of all days of month separated by weeks as a keys
            $max = 7;
            if ($i ==1){ $max = 8 - $monthStartDay;}
            if ($i == $numOfweeks){ $max = $monthEndingDay;}
            for ($r=1; $r<=$max; $r++){

                    $week_array[$i][]=$date;
                    $date = date('Y/m/d',strtotime($date . "+1 days"));
            }
    }
    $new_datenew = date('Y/m/d', strtotime($datenew));
    $week_result='';
        foreach ($week_array as $key => $val){  /// finding what week number of my date from week_array
            foreach ($val as $kr => $value){
            if ($new_datenew == $value){
                $week_result = $key;
            } 
            }
        }
    return $week_result;
}
print week_number_within_month('2016-09-15');

答案 21 :(得分:0)

来自碳:

return (int) ceil((new Datetime())->format('d') / 7);

尽可能简单:)

答案 22 :(得分:0)

我使用这个简单的功能:

function weekNumberInMonth($timestampDate)
{
    $firstDayOfMonth = strtotime(date('01-M-Y 00:00:00', $timestampDate));
    $firstWeekdayOfMonth = date( 'w', $firstDayOfMonth);
    $dayNumberInMonth = date('d', $timestampDate);
    $weekNumberInMonth = ceil(($dayNumberInMonth + $firstWeekdayOfMonth) / 7);
    return $weekNumberInMonth;
}

答案 23 :(得分:0)

简短而万无一失:

// Function accepts $date as a string,
// Returns the week number in which the given date falls.
// Assumed week starts on Sunday.
function wom($date) {
  $date = strtotime($date);
  $weeknoofday = date('w', $date);
  $day = date('j', $date);
  $weekofmonth = ceil(($day + (7-($weeknoofday+1))) / 7);
  return $weekofmonth;
}
// Test
foreach (range(1, 31) as $day) {
    $test_date = "2015-01-" . str_pad($day, 2, '0', STR_PAD_LEFT);
    echo "$test_date - ";
    echo wom($test_date) . "\n";
}

答案 24 :(得分:0)

你可以在较新的php版本中使用W. http://php.net/manual/en/function.date.php

我已经像这样使用它了:

function getWeek($date) { 
$month_start=strtotime("1 ".date('F Y',$date));
$current_date=strtotime(date('j F Y',$date));

$month_week=date("W",$month_start);
$current_week=date("W",$current_date);
return ($current_week-$month_week);

}//0 is the week of the first.

答案 25 :(得分:0)

我在网上找到了这个: http://kcwebprogrammers.blogspot.de/2009/03/current-week-in-month-php.html

他有一个非常简单的解决方案,似乎对我来说很好。

$currentWeek = ceiling((date("d") - date("w") - 1) / 7) + 1;

例如:

$now = strtotime("today");
$weekOfMonth = ceil((date("d", $now) - date("w", $now) - 1) / 7) + 1;

答案 26 :(得分:0)

我真的很喜欢@ michaelc的回答。但是,我陷入了几个问题。似乎每当星期天到来时,都会有一个偏移。我认为这与一周的哪一天是一周的开始有关。在任何情况下,这是我对它的轻微改动,为了可读性而扩展了一点:

function wom(\DateTime $date) {
    // The week of the year of the current month
    $cw = date('W', $date->getTimestamp());

    // The week of the year of the first of the given month
    $fw = date('W',strtotime(date('Y-m-01',$date->getTimeStamp())));

    // Offset
    $o = 1;

    // If it is a Saturday, offset by two.
    if( date('N',$date->getTimestamp()) == 7 ) {
        $o = 2;
    }

    return $cw -$fw + $o;
}

所以如果日期是2013年11月9日......

$cw = 45
$fw = 44

并且偏移量为1,它正确返回2.

如果日期是2013年11月10日,则$cw$fw与之前相同,但偏移量为2,并且正确返回3.

答案 27 :(得分:0)

function get_week_of_month( $timestamp )
{
    $week_of_month = 0; 
    $month = date( 'j', $timestamp );
    $test_month = $month;
    while( $test_month == $month )
    {
        $week_of_month++;
        $timestamp = strtotime( '-1 week', $timestamp );
        $test_month = date( 'j', $timestamp );
    }
    return $week_of_month;
}

答案 28 :(得分:0)

经过大量的努力,我找到了解决方案

<?php

function getWeeks($month,$year)
{
    $month = intval($month);        //force month to single integer if '0x'
    $suff = array('st','nd','rd','th','th','th');       //week suffixes
    $end = date('t',mktime(0,0,0,$month,1,$year));      //last date day of month: 28 - 31
    $start = date('w',mktime(0,0,0,$month,1,$year));    //1st day of month: 0 - 6 (Sun - Sat)
    $last = 7 - $start;                     //get last day date (Sat) of first week
    $noweeks = ceil((($end - ($last + 1))/7) + 1);      //total no. weeks in month
    $output = "";                       //initialize string     
    $monthlabel = str_pad($month, 2, '0', STR_PAD_LEFT);
    for($x=1;$x<$noweeks+1;$x++)
    {   
        if($x == 1)
        {
            $startdate = "$year-$monthlabel-01";
            $day = $last - 6;
        }
        else
        {
            $day = $last + 1 + (($x-2)*7);
            $day = str_pad($day, 2, '0', STR_PAD_LEFT);
            $startdate = "$year-$monthlabel-$day";
        }
        if($x == $noweeks)
        {
            $enddate = "$year-$monthlabel-$end";
        }
        else
        {
            $dayend = $day + 6;
            $dayend = str_pad($dayend, 2, '0', STR_PAD_LEFT);
            $enddate = "$year-$monthlabel-$dayend";
        }
        $j=1;
        if($j--)
        {
            $k=getTotalDate($startdate,$enddate);
            $j=1;
        }

    $output .= "Week ".$xyz." week -> Start date=$startdate End date=$enddate <br />";  
    }
    return $output;
}

if(isset($_POST) && !empty($_POST)){
    $month = $_POST['m'];
    $year = $_POST['y']; 
    echo getWeeks($month,$year);
}
?>

<form method="post">
  M:
  <input name="m" value="" />
  Y:
  <input name="y" value="" />
  <input type="submit" value="go" />
</form>

答案 29 :(得分:0)

Python: Number of the Week in a Month

这是Python中的一个有用的例子 - 应该很容易转换。