How to get weeks starting on sunday?

前端 未结 9 1635
甜味超标
甜味超标 2020-12-03 19:25

I need to get week number in php where week should be calculated from sunday. By default its from monday. Please help me to find a way how to get week number considering sun

相关标签:
9条回答
  • 2020-12-03 19:27

    Try this one. to get sunday day must -1 day.

    $date = "2015-05-25";
    echo date("W", strtotime("-1 day",strtotime($date)));
    
    0 讨论(0)
  • 2020-12-03 19:30

    Try this:

    $week = intval(date('W'));
    
    if (date('w') == 0) {            // 0 = Sunday
       $week++;
    }
    
    echo $week;
    

    Not sure if the logic is right though;

    0 讨论(0)
  • 2020-12-03 19:34

    Tested in php 5.6 Debian 7

    function getWeekNumber(\DateTime $_date)
    {
        $week = intval($_date->format('W'));
    
        if(intval($_date->format('w')) == 0) {
            $week = intval($_date->format('W')) == ( 52 + intval($_date->format('L')) ) ? 1 : $week + 1;
        }
    
        return $week;
    }
    
    0 讨论(0)
  • 2020-12-03 19:36

    You should try with strftime

    $week_start = new DateTime();
    $week = strftime("%U");  //this gets you the week number starting Sunday
    $week_start->setISODate(2012,$week,0); //return the first day of the week with offset 0
    echo $week_start -> format('d-M-Y'); //and just prints with formatting 
    
    0 讨论(0)
  • 2020-12-03 19:43

    To expand on silkfire answer and allow for it wrapping around years

       if($date->format('w') == 0){
            if(date('W',strtotime($date->format('Y')."-12-31"))==52 and $date->format('W') == 52){
                $week = 1;
            }
            elseif(date('W',strtotime($date->format('Y')."-12-31"))==53 and $date->format('W') == 53){
                $week = 1;
            }
            else{
                $week++;
            }
        }
    
    0 讨论(0)
  • 2020-12-03 19:47

    I solved this like this:

    function getWeekOfYear( DateTime $date ) {
    
            $dayOfweek = intval( $date->format('w') );
    
            if( $dayOfweek == 0 ) {
                $date->add(new DateInterval('P1D'));
            } 
    
            $weekOfYear = intval( $date->format('W') );
    
            return $weekOfYear;
    }
    
    0 讨论(0)
提交回复
热议问题