1
\$\begingroup\$

Is this an efficient way to do this?

the code is designed to find the nearest friday, without passing Sunday. If it is already past Friday, the start date should equal now.

function get_weekend(){
        $start = time();
        $day = date('w',$now);

        //find friday, without going past Sunday
        while ($day < 5 && $day > 0){
            $start = $start + 86400;
            $day = date('w',$start);
        }

        //find nearest sunday to start date
        $end = $start;
        while ($day != 0){
            $end = $end + 86400;
            $day = date('w',$end);
        }
        $weekend['StartDate']=date("d-F-Y",$start);
        $weekend['EndDate'] = date("d-F-Y",$end);
        return $weekend;

    }
\$\endgroup\$
1
\$\begingroup\$

No need for while loops - just some math:

function get_weekend()
{
    $start = time();
    $end = $start;
    $day = date('w', $start);

    if ($day > 0 && $day < 5)
    {
        $start = $time()+ ((5 - $day) * 86400);
    }

    if ($day != 0)
    {
        $end = time() + (7 - $day) * 86400;
    }

    $weekend['StartDate'] = date('d-F-Y', $start);
    $weekend['EndDate'] = date('d-F-Y', $end);

    return $weekend;
}

Edit: Found there was a better way to calculate $end;

Edit: Keep finding better code:

function get_weekend()
{
    $start = time();
    $end = $start;
    $day = date('w', $start);

    if ($day > 0)
    {
        if ($day < 5)
        {
            $start += ((5 - $day) * 86400);
        }

        $end += (7 - $day) * 86400;
    }

    $weekend['StartDate'] = date('d-F-Y', $start);
    $weekend['EndDate'] = date('d-F-Y', $end);

    return $weekend;
}
\$\endgroup\$
2
\$\begingroup\$

Short, short version:

function get_weekend()
{
    $fri = strtotime('friday');
    $sun = strtotime('sunday');
    // strtotime('friday') will be after strtotime('sunday') if it is after 0:00 Friday
    // and before 0:00 on Sunday
    $start = $sun < $fri? now():$fri;
    $weekend = array();
    $weekend['StartDate'] = date('d-F-Y', $start);
    $weekend['EndDate'] = date('d-F-Y', $end);
    return $weekend;
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.