Get week number (in the year) from a date PHP

前端 未结 17 2063
星月不相逢
星月不相逢 2020-11-27 14:54

I want to take a date and work out its week number.

So far, I have the following. It is returning 24 when it should be 42.



        
17条回答
  •  长情又很酷
    2020-11-27 15:24

    How about using the IntlGregorianCalendar class?

    Requirements: Before you start to use IntlGregorianCalendar make sure that libicu or pecl/intl is installed on the Server. So run on the CLI:

    php -m
    

    If you see intl in the [PHP Modules] list, then you can use IntlGregorianCalendar.

    DateTime vs IntlGregorianCalendar: IntlGregorianCalendar is not better then DateTime. But the good thing about IntlGregorianCalendar is that it will give you the week number as an int.

    Example:

    $dateTime = new DateTime('21-09-2020 09:00:00');
    echo $dateTime->format("W"); // string '39'
    
    $intlCalendar = IntlCalendar::fromDateTime ('21-09-2020 09:00:00');
    echo $intlCalendar->get(IntlCalendar::FIELD_WEEK_OF_YEAR); // integer 39
    

提交回复
热议问题