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

前端 未结 17 1865
星月不相逢
星月不相逢 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:32

    This get today date then tell the week number for the week

    <?php
     $date=date("W");
     echo $date." Week Number";
     ?>
    
    0 讨论(0)
  • 2020-11-27 15:34

    Today, using PHP's DateTime objects is better:

    <?php
    $ddate = "2012-10-18";
    $date = new DateTime($ddate);
    $week = $date->format("W");
    echo "Weeknummer: $week";
    

    It's because in mktime(), it goes like this:

    mktime(hour, minute, second, month, day, year);
    

    Hence, your order is wrong.

    <?php
    $ddate = "2012-10-18";
    $duedt = explode("-", $ddate);
    $date  = mktime(0, 0, 0, $duedt[1], $duedt[2], $duedt[0]);
    $week  = (int)date('W', $date);
    echo "Weeknummer: " . $week;
    ?>
    
    0 讨论(0)
  • 2020-11-27 15:34

    for get week number in jalai calendar you can use this:

    $weeknumber = date("W"); //number week in year
    $dayweek = date("w"); //number day in week
    if ($dayweek == "6")
    {
        $weeknumberint = (int)$weeknumber;
        $date2int++; 
        $weeknumber = (string)$date2int;
    }
    
    echo $date2;
    

    result:

    15
    

    week number change in saturday

    0 讨论(0)
  • 2020-11-27 15:34

    The most of the above given examples create a problem when a year has 53 weeks (like 2020). So every fourth year you will experience a week difference. This code does not:

    $thisYear = "2020";
    $thisDate = "2020-04-24"; //or any other custom date
    $weeknr = date("W", strtotime($thisDate)); //when you want the weeknumber of a specific week, or just enter the weeknumber yourself
    
    $tempDatum = new DateTime();
    $tempDatum->setISODate($thisYear, $weeknr);
    $tempDatum_start = $tempDatum->format('Y-m-d');
    $tempDatum->setISODate($thisYear, $weeknr, 7);
    $tempDatum_end = $tempDatum->format('Y-m-d');
    
    echo $tempDatum_start //will output the date of monday
    echo $tempDatum_end // will output the date of sunday
    
    0 讨论(0)
  • 2020-11-27 15:37
    <?php
    $ddate = "2012-10-18";
    $duedt = explode("-",$ddate);
    $date = mktime(0, 0, 0, $duedt[1], $duedt[2],$duedt[0]);
    $week = (int)date('W', $date);
    echo "Weeknummer: ".$week;
    ?>
    

    You had the params to mktime wrong - needs to be Month/Day/Year, not Day/Month/Year

    0 讨论(0)
提交回复
热议问题