Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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;

    }
share|improve this question

2 Answers 2

up vote 1 down vote accepted

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;
}
share|improve this answer

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;
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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