Get week number in month from date in PHP?

前端 未结 14 2227
说谎
说谎 2020-11-28 11:15

I have an array of random dates (not coming from MySQL). I need to group them by the week as Week1, Week2, and so on upto Week5.

What I have is this:



        
14条回答
  •  伪装坚强ぢ
    2020-11-28 12:10

    I think this relationship should be true and come in handy:

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

    Implemented in PHP you get this:

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

    To get weeks that starts with sunday, simply replace both date("W", ...) with strftime("%U", ...).

提交回复
热议问题