How to get weeks starting on sunday?

前端 未结 9 1636
甜味超标
甜味超标 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:48

    I know this topic is old, but this is a shorter way to do it with elvis operator and "+7 day" expression for strtotime():

    $week=date("W",strtotime(date("w")==1?"+7 day":"+0 day"));
    

    if $date("w") returns true means today is a day between tuesday and sunday (1-6), so, we can return today week ('today').

    if returns false, it means is monday (0), so, we should return the next day ('+1 week').

    This way we don't need to care about last or first day of year or check if current year has 52 or 53 weeks.

    Edited: the previous answer (and others in this topic) doesn't work for this year because januray 1st is monday, so, it needs to be 1 week ago (-1 week) excluding sunday (day 6).

    date("W",strtotime(date("w")?'-7 day':'+0 day'));
    

    I think a condition asking if januray 1st is monday could work, but I didn't test it yet, I will come back with an answer later

    For a custom day you could use this:

    $date = strtotime('2018-04-30'); // (it is monday)
    
    if(date("w",strtotime(date('Y',$date).'-01-01'))==1){ // if first day of year is monday
        $week = strtotime(date('w',$date)?"-7 day":"+0 day",$date); // and today is sunday, sub a week
        $week = date("W",$week);
    }else{ // if is not monday
        $week = strtotime(date('w',$date)==1?"+7 day":"+0 day",$date); // and today is monday, add a week
        $week = date("W",$week);
    }
    
    0 讨论(0)
  • 2020-12-03 19:52

    The first solution is not correct on Jan 01, 2017 or any year that begins on a Sunday.

    Try this:

    $date = date('Y-m-d');
    echo strftime("%U", strtotime($date ) );
    
    0 讨论(0)
  • 2020-12-03 19:52

    Building on @silkfire's answer:

        $year = date('Y');
        $week_no = date('W');
        if (date('w') == 0) {            // 0 = Sunday
           $week_no++;
        }
        // We shifted the week but the week still starts on a Monday.
        $weekStartDate = new DateTime();
        $weekStartDate->setISODate($year,$week_no);
        // Shift start date to Sunday
        $weekStartDate->add(DateInterval::createFromDateString('-1 day')); 
    
    0 讨论(0)
提交回复
热议问题