Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

php - how to find number of mondays or tuesdays between two dates?

I have start date and end date.

I need to find out the day that is Sunday or Monday etc dependent upon user click on check box.

How can I find/calculate that in PHP?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The answer by w35I3y was almost correct, but I was getting errors using that function. This function correctly calculates the number of Mondays or any specific day between two given dates:

/** 
* Counts the number occurrences of a certain day of the week between a start and end date
* The $start and $end variables must be in UTC format or you will get the wrong number 
* of days  when crossing daylight savings time
* @param - $day - the day of the week such as "Monday", "Tuesday"...
* @param - $start - a UTC timestamp representing the start date
* @param - $end - a UTC timestamp representing the end date
* @return Number of occurences of $day between $start and $end
*/
function countDays($day, $start, $end)
{        
    //get the day of the week for start and end dates (0-6)
    $w = array(date('w', $start), date('w', $end));

    //get partial week day count
    if ($w[0] < $w[1])
    {            
        $partialWeekCount = ($day >= $w[0] && $day <= $w[1]);
    }else if ($w[0] == $w[1])
    {
        $partialWeekCount = $w[0] == $day;
    }else
    {
        $partialWeekCount = ($day >= $w[0] || $day <= $w[1]);
    }

    //first count the number of complete weeks, then add 1 if $day falls in a partial week.
    return floor( ( $end-$start )/60/60/24/7) + $partialWeekCount;
}

Example Usage:

$start = strtotime("tuesday UTC");    
$end = strtotime("3 tuesday UTC");       
echo date("m/d/Y", $start). " - ".date("m/d/Y", $end). " has ". countDays(0, $start, $end). " Sundays";

Outputs something like: 09/28/2010 - 10/19/2010 has 3 Sundays.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...