代码之家  ›  专栏  ›  技术社区  ›  michaelmcgurk

用PHP显示周数[duplicate]

php
  •  0
  • michaelmcgurk  · 技术社区  · 7 年前

    我有一个随机日期数组(不是来自MySQL)。我需要按周将它们分组为第1周、第2周等,直到第5周。

    $dates = array('2015-09-01','2015-09-05','2015-09-06','2015-09-15','2015-09-17');
    

    我需要的是一个函数,通过提供日期来获取每月的周数。

    date('W',strtotime('2015-09-01')); 但本周数是年份(1-52)之间的数字,但我只需要该月的周数,例如2015年9月有5周:

    • 第1周=第1至第5周
    • 第2周=第6至第12周
    • 第3周=13到19
    • 第5周=27日至30日

    例如

    $weekNumber = getWeekNumber('2015-09-01') //output 1;
    $weekNumber = getWeekNumber('2015-09-17') //output 3;
    
    0 回复  |  直到 10 年前
        1
  •  33
  •   Anders Atiqur    7 年前

    我认为这种关系应该是真实的,而且会派上用场:

    Week of the month = Week of the year - Week of the year of first day of month + 1
    

    function weekOfMonth($date) {
        //Get the first day of the month.
        $firstOfMonth = strtotime(date("Y-m-01", $date));
        //Apply above formula.
        return intval(date("W", $date)) - intval(date("W", $firstOfMonth)) + 1;
    }
    

    要想得到从周日开始的周数,只需将两者都替换掉 date("W", ...) strftime("%U", ...) .

        2
  •  12
  •   Matteo Tassinari    10 年前

    您可以使用下面的函数,完全注释:

    /**
     * Returns the number of week in a month for the specified date.
     *
     * @param string $date
     * @return int
     */
    function weekOfMonth($date) {
        // estract date parts
        list($y, $m, $d) = explode('-', date('Y-m-d', strtotime($date)));
    
        // current week, min 1
        $w = 1;
    
        // for each day since the start of the month
        for ($i = 1; $i <= $d; ++$i) {
            // if that day was a sunday and is not the first day of month
            if ($i > 1 && date('w', strtotime("$y-$m-$i")) == 0) {
                // increment current week
                ++$w;
            }
        }
    
        // now return
        return $w;
    }
    
        3
  •  10
  •   Goendg    10 年前

    function weekOfMonth($date) {
        $firstOfMonth = date("Y-m-01", strtotime($date));
        return intval(date("W", strtotime($date))) - intval(date("W", strtotime($firstOfMonth)));
    }
    
        4
  •  4
  •   Asif Hussain    10 年前

    我自己创建了这个函数,似乎可以正常工作。如果其他人有更好的方法,请分享。。这是我所做的。

    function weekOfMonth($qDate) {
        $dt = strtotime($qDate);
        $day  = date('j',$dt);
        $month = date('m',$dt);
        $year = date('Y',$dt);
        $totalDays = date('t',$dt);
        $weekCnt = 1;
        $retWeek = 0;
        for($i=1;$i<=$totalDays;$i++) {
            $curDay = date("N", mktime(0,0,0,$month,$i,$year));
            if($curDay==7) {
                if($i==$day) {
                    $retWeek = $weekCnt+1;
                }
                $weekCnt++;
            } else {
                if($i==$day) {
                    $retWeek = $weekCnt;
                }
            }
        }
        return $retWeek;
    }
    


    echo weekOfMonth('2015-09-08') // gives me 2;
    
        5
  •  3
  •   Community Mohan Dere    9 年前
    function getWeekOfMonth(DateTime $date) {
        $firstDayOfMonth = new DateTime($date->format('Y-m-1'));
    
        return ceil(($firstDayOfMonth->format('N') + $date->format('j') - 1) / 7);
    }
    

    Goendg solution 不适用于2016-10-31。

        6
  •  2
  •   Marlon Ingal    8 年前
    function weekOfMonth($strDate) {
      $dateArray = explode("-", $strDate);
      $date = new DateTime();
      $date->setDate($dateArray[0], $dateArray[1], $dateArray[2]);
      return floor((date_format($date, 'j') - 1) / 7) + 1;  
    }
    

    weekofmount('2015-09-17')//返回3

        7
  •  1
  •   Mark Reed    10 年前

    给定月1日的时间(0=星期日到6=星期六) firstWday ,返回该月内的(基于星期日的)周数:

    weekOfMonth = floor((dayOfMonth + firstWday - 1)/7) + 1 
    

    翻译成PHP:

    function weekOfMonth($dateString) {
      list($year, $month, $mday) = explode("-", $dateString);
      $firstWday = date("w",strtotime("$year-$month-1"));
      return floor(($mday + $firstWday - 1)/7) + 1;
    }
    
        8
  •  1
  •   Ajay Tambe    7 年前

    $currentWeek = ceil((date("d",strtotime($today_date)) - date("w",strtotime($today_date)) - 1) / 7) + 1;
    

    算法:

    日期='2018-08-08'=>Y-m-d

    1. 找出一周中某一天减去1(一周中的天数)的数字表示,例如(3-1)
    2. 除以7得到结果,然后计算结果的值
    3. 结果加1,如ceil((08-3)-1)/7)+1=2
        9
  •  1
  •   Andrew Vasiliev    7 年前

    function GetWeekNumberOfMonth ($date){
        echo $date -> format('d.m.Y');
        //define current year, month and day in numeric
        $_year = $date -> format('Y');
        $_month = $date -> format('n');
        $_day = $date -> format('j');
        $_week = 0; //count of weeks passed
        for ($i = 1; $i < $_day; $i++){
            echo "\n\n-->";
            $_newDate = mktime(0,0,1, $_month, $i, $_year);
            echo "\n";
            echo date("d.m.Y", $_newDate);
            echo "-->";
            echo date("N", $_newDate);
            //on sunday increasing weeks passed count
            if (date("N", $_newDate) == 7){
                echo "New week";
                $_week += 1;
            }
    
        }
        return $_week + 1; // as we are counting only passed weeks the current one would be on one higher
    }
    
    $date = new DateTime("2019-04-08");
    echo "\n\nResult: ". GetWeekNumberOfMonth($date);
    
        10
  •  0
  •   Lionser    7 年前
    // self::DAYS_IN_WEEK = 7;
    function getWeeksNumberOfMonth(): int
    {
        $currentDate            = new \DateTime();
        $dayNumberInMonth       = (int) $currentDate->format('j');
        $dayNumberInWeek        = (int) $currentDate->format('N');
        $dayNumberToLastSunday  = $dayNumberInMonth - $dayNumberInWeek;
        $daysCountInFirstWeek   = $dayNumberToLastSunday % self::DAYS_IN_WEEK;
        $weeksCountToLastSunday = ($dayNumberToLastSunday - $daysCountInFirstWeek) / self::DAYS_IN_WEEK;
    
        $weeks = [];
        array_push($weeks, $daysCountInFirstWeek);
        for ($i = 0; $i < $weeksCountToLastSunday; $i++) {
            array_push($weeks, self::DAYS_IN_WEEK);
        }
        array_push($weeks, $dayNumberInWeek);
    
        if (array_sum($weeks) !== $dayNumberInMonth) {
            throw new Exception('Logic is not valid');
        }
    
        return count($weeks);
    }
    

    短变型:

    (int) (new \DateTime())->format('W') - (int) (new \DateTime('first day of this month'))->format('W') + 1;
    
        11
  •  0
  •   Ivijan Stefan Stipić    6 年前

    有很多解决方案,但这里有一个我的解决方案,在大多数情况下都很有效。

    function current_week ($date = NULL) {
        if($date) {
            if(is_numeric($date) && ctype_digit($date) && strtotime(date('Y-m-d H:i:s',$date)) === (int)$date)
                $unix_timestamp = $date;
            else
                $unix_timestamp = strtotime($date);
        } else $unix_timestamp = time();
    
        return (ceil((date('d', $unix_timestamp) - date('w', $unix_timestamp) - 1) / 7) + 1);
    }
    

    time()

    享受吧!

        12
  •  0
  •   Emre Erdoğan    6 年前

    $datetime0 = date_create("1970-01-01");
    $datetime1 = date_create(date("Y-m-d",mktime(0,0,0,$m,"01",$Y)));
    $datetime2 = date_create(date("Y-m-d",mktime(0,0,0,$m,$d,$Y)));
    
    $interval1 = date_diff($datetime0, $datetime1);
    $daysdiff1= $interval1->format('%a');
    
    $interval2 = date_diff($datetime0, $datetime2);
    $daysdiff2= $interval2->format('%a');
    
    $week1=round($daysdiff1/7);
    $week2=round($daysdiff2/7);
    
    $WeekOfMonth=$week2-$week1+1;
    
        13
  •  0
  •   danvin    6 年前
    $date = new DateTime('first Monday of this month');
    $thisMonth = $date->format('m');
    $mondays_arr = [];
    
    // Get all the Mondays in the current month and store in array
    while ($date->format('m') === $thisMonth) {
        //echo $date->format('Y-m-d'), "\n";
        $mondays_arr[] = $date->format('d');
        $date->modify('next Monday');
    }
    
    // Get the day of the week (1-7 from monday to sunday)
    $day_of_week = date('N') - 1;
    
    // Get the day of month (1 to 31) 
    $current_week_monday_date = date('j') - $day_of_week;
    
    /*$day_of_week = date('N',mktime(0, 0, 0, 2, 11, 2020)) - 1;
    $current_week_monday_date = date('j',mktime(0, 0, 0, 2, 11, 2020)) - $day_of_week;*/
    
    $week_no = array_search($current_week_monday_date,$mondays_arr) + 1;
    echo "Week No: ". $week_no;
    
        14
  •  -2
  •   Anders Atiqur    8 年前
    //It's easy, no need to use php function
    //Let's say your date is 2017-07-02
    
    $Date = explode("-","2017-07-02");
    $DateNo = $Date[2];
    $WeekNo = $DateNo / 7; // devide it with 7
    if(is_float($WeekNo) == true)
    {
       $WeekNo = ceil($WeekNo); //So answer will be 1
    }  
    
    //If value is not float then ,you got your answer directly
    
    推荐文章