Closed Thread
Results 1 to 11 of 11




  

Thread: Retrieve the number of weekdays with php

      
  1. #1
    Jedi Master Paramiliar is on a distinguished road Paramiliar's Avatar
    Join Date
    July 24, 2007
    Location
    West Midlands
    Posts
    105
    Rep Power
    5
    Feedback Score
    0

    Default Retrieve the number of weekdays with php

    Hey guys need some help on this one. I need a function that will return the number of days between two dynamic dates.

    I then need to expand it to display the number of saturdays and the number of sundays in this date range as well.

    Havn't a clue where to start with this one

    I mean getting the number of days is easy using a timestamp the problem is finding the number of saturdays and number of sundays

    Paramiliar added 42 Minutes and 20 Seconds later...

    I have eventually come up with this but as you can imagine it takes a while to run (0.2 seconds to be precise) and with the query I will be running it will take even longer to run if anyone can improve on it let me know


    PHP Code:
        function CheckHolidays($thisDay) {    
            
    $arrTargetDate=getdate($thisDay);
            
    // Calculate Public Holidays
            
    @sqlconnect();
    //        $conn = auth_db_connect();
            
    $holiday_sql "SELECT date FROM public_holidays WHERE date = FROM_UNIXTIME($thisDay)";
            
    $result mysql_query($holiday_sql);
            
    $holiday mysql_fetch_row($result);
            @
    mysql_free_result($result);

            if (
    $holiday) {
                    if(
    $debug) {
                        echo 
    "<small><b>".date("d.m.y",$thisDay)." is a Holiday!</b></small><br>";
                        }
                    return 
    TRUE;
                    }
                
    // here we need to check, whether day is a saturday
                //elseif($arrTargetDate['wday']==6 || $arrTargetDate['wday']==0) {
                //    if($debug) {
            //            echo "<small><b>".date("d.m.y",$thisDay)." is on a weekend!</b></small><br>";
                //        }
            //        return TRUE;
            //        }

            
    return FALSE;
            }
        
        
        function 
    workingdays($startdate$enddate){
            
    $startdate explode("/"$startdate); //format dd/mm/YYYY
            
    $enddate explode("/"$enddate); //format dd/mm/YYYY
            
    $starttime mktime('0''0''0'$startdate[1], $startdate[0], $startdate[2]);
            
    $endtime mktime('0''0''0'$enddate[1], $enddate[0], $enddate[2]);
            
            
    $noofdays ceil(($endtime $starttime) / (60 60 24)) + 1;
            
    $sundaycounter 0;
            
    $saturdaycounter 0;
            
    $weekdaycounter 0;
            
    $holidaycounter 0;
            
            echo 
    "No. of days = ".$noofdays."<br>";
            
            for (
    $i 0$i $noofdays$i++){
                
    $ts mktime('0''0''0'$startdate[1], ($startdate[0] + $i), $startdate[2]);
                
    $test=CheckHolidays($ts);
                if(
    $test == TRUE) {
                    
    $holidaycounter++;
                } else {
                    if (
    date("l"$ts) == "Sunday"){
                        
    $sundaycounter ++;
                    } elseif (
    date("l"$ts) == "Saturday"){
                        
    $saturdaycounter ++;
                    } else {
                        
    $weekdaycounter ++;
                    }
                }
            }
            
            echo 
    "stats are<br>~~~~~~~~~<br>Sundays = ".$sundaycounter."<br>Saturdays = ".$saturdaycounter."<br> Weekdays = ".$weekdaycounter."<br> Bank holidays = ".$holidaycounter;
        }
        
        
        
    $startdate "01/01/2007";
        
    $enddate "12/01/2008";
        
        
    workingdays($startdate$enddate);
        
        
        
    $benchtime_e microtime_float();
        
    $time $benchtime_e $benchtime_s;

        echo 
    "<br><br>Ran in $time seconds\n"
    Last edited by Paramiliar; Jan 10th, 2008 at 4:31 am. Reason: Automerged Doublepost
    Matthew Bagley
    Paramiliar Design Studios
    IT Consultant | Website Design | Website Development

  2. #2
    Grand Masters Colleen has a reputation beyond reputeColleen has a reputation beyond reputeColleen has a reputation beyond reputeColleen has a reputation beyond reputeColleen has a reputation beyond reputeColleen has a reputation beyond reputeColleen has a reputation beyond reputeColleen has a reputation beyond reputeColleen has a reputation beyond reputeColleen has a reputation beyond reputeColleen has a reputation beyond repute Colleen's Avatar
    Join Date
    September 22, 2006
    Location
    Canada
    Posts
    11,144
    Rep Power
    26
    Feedback Score
    0

    Default

    hmm... any programmers around here?

  3. #3
    Jedi Master JHalstead will become famous soon enoughJHalstead will become famous soon enoughJHalstead will become famous soon enough JHalstead's Avatar
    Join Date
    January 3, 2008
    Location
    OKC, OK - USA
    Posts
    147
    Rep Power
    5
    Feedback Score
    0

    Default

    The best I can find is this:

    <?php
    echo datediff('01/01/2008', '01/18/2008', false);

    function datediff($datefrom, $dateto, $using_timestamps = false) {
    if (!$using_timestamps) {
    $datefrom = strtotime($datefrom, 0);
    $dateto = strtotime($dateto, 0);
    }
    $difference = $dateto - $datefrom; // Difference in seconds
    // Number of full weekdays
    $days_difference = floor($difference / 86400);
    // Complete weeks
    if(abs($days_difference) >= 7) {
    $weeks_difference = floor($days_difference / 7);
    } else {
    $weeks_difference = 0;
    }
    $first_day = date("w", $datefrom);
    $days_remainder = floor($days_difference % 7);
    $odd_days = $first_day + $days_remainder; // Do we have a Saturday or Sunday in the remainder?
    if ($odd_days > 7) { // Sunday
    $days_remainder--;
    }
    if ($odd_days > 6) { // Saturday
    $days_remainder--;
    }
    $datediff = ($weeks_difference * 5) + $days_remainder;
    return $datediff+2;
    }
    ?>

    Found it here http://www.ilovejackdaniels.com/php/...diff-function/ actually. I don't know if it's any faster but something you can look into. Hope this helps.

  4. #4
    Idolized By All noppid is just really nicenoppid is just really nicenoppid is just really nicenoppid is just really nicenoppid is just really nicenoppid is just really nicenoppid is just really nice noppid's Avatar
    Join Date
    October 12, 2006
    Location
    Florida
    Posts
    487
    Rep Power
    6
    Feedback Score
    0

    Default

    I hate time math. But I'm curious if you solved this yet? these things are like puzzles that get under my skin.

    EDIT: After a closer look, if your math works, then you are done there. I'm willing to bet the farm your performance hit is in that query and or the table design.

    EDIT EDIT: OMG! You are recreating the mysql connection for every call to your function.

    P.S. You owe me a farm. I can guarantee mysql is your problem, not math calculation time.


    Cheers.
    Free vBulletin hacks and vBulletin Support.
    Talk to bikers around the world about motorcycles.
    Clogging an american dance step.

  5. #5
    Jedi Master Thor Erik is on a distinguished road Thor Erik's Avatar
    Join Date
    January 8, 2008
    Location
    <.< not in oslo soon
    Posts
    33
    Rep Power
    5
    Feedback Score
    0

    Default

    Quote Originally Posted by noppid View Post
    I hate time math. But I'm curious if you solved this yet? these things are like puzzles that get under my skin.

    EDIT: After a closer look, if your math works, then you are done there. I'm willing to bet the farm your performance hit is in that query and or the table design.

    EDIT EDIT: OMG! You are recreating the mysql connection for every call to your function.

    P.S. You owe me a farm. I can guarantee mysql is your problem, not math calculation time.


    Cheers.
    Hehe, true, move the mysql connection creation outside the function, that way you preserve the connection, and just re-use it every time you call


    JHalstead's code looks good, maybe something you're looking for.
    else you might find something here:
    PEAR :: Search: date
    aditionaly Zend framework got some date handeling ready:
    Zend Framework: Documentation

  6. #6
    Jedi Master Paramiliar is on a distinguished road Paramiliar's Avatar
    Join Date
    July 24, 2007
    Location
    West Midlands
    Posts
    105
    Rep Power
    5
    Feedback Score
    0

    Default

    sorry guys not been getting the emails, the sqlconnection is only made if a connection isn't already open so I am not making a connection everytime the function runs lol and as for the problem yes I managed to solve it an hour after posting (always the way) I'll post the script up here when I am at work tomorrow but basicly it checks if the day is a sat and sun and increments the counter occordingly and adds that onto the end value so it can work out the end date of 14 business days in the future (with support for setting sat and sunday as working days)
    Matthew Bagley
    Paramiliar Design Studios
    IT Consultant | Website Design | Website Development

  7. #7
    Idolized By All noppid is just really nicenoppid is just really nicenoppid is just really nicenoppid is just really nicenoppid is just really nicenoppid is just really nicenoppid is just really nice noppid's Avatar
    Join Date
    October 12, 2006
    Location
    Florida
    Posts
    487
    Rep Power
    6
    Feedback Score
    0

    Default

    Good deal. I read that as mysql_connect() failing to see it was a custom function.

    But in any event, do tell your solution.
    Free vBulletin hacks and vBulletin Support.
    Talk to bikers around the world about motorcycles.
    Clogging an american dance step.

  8. #8
    Jedi Master Paramiliar is on a distinguished road Paramiliar's Avatar
    Join Date
    July 24, 2007
    Location
    West Midlands
    Posts
    105
    Rep Power
    5
    Feedback Score
    0

    Default

    here is the code

    if anyone wants me to post the check_holiday_range() function let me know but all it does is check a database with the timestamp range and gets the number of rows

    PHP Code:
    /*
    **    Function     :    getworkingdays_time
    **    Attributes    :    $STARTSTAMP = timestamp of the start day
    **                :    $ENDSTAMP = timestamp of the end day
    **    Description    :    returns the number of extra working days to be added
    **                    worked out by adding the number of bank holidays, 
    **                    the number of saturdays they do not work and
    **                    the number of sundays they do not work.
    */
        
    function getworkingdays_time($STARTSTAMP$ENDSTAMP){
            
    $noofdays ceil(($ENDSTAMP $STARTSTAMP) / 86400);
            
    $sundaycounter 0;
            
    $saturdaycounter 0;
            
    $holidaycounter 0;
            
    $offset 0;
            
    $holidaycounter check_holiday_range($STARTSTAMP$ENDSTAMP);        // check holiday range
            
            
    for ($i 0$i <= $noofdays$i++){
                
    $ts $STARTSTAMP + ($i 86400);
                if (
    WORKSATURDAYS == '0' && date("l"$ts) == "Saturday"){
                    
    ## they dont work saturdays
                    
    $saturdaycounter ++;
                } elseif (
    WORKSUNDAYS == '0' && date("l"$ts) == "Sunday"){
                    
    ## they dont work sundays
                    
    $sundaycounter ++;
                }        
            }
            
    $total $holidaycounter $saturdaycounter $sundaycounter;
            
    $offset $total;
            if (
    $total 0){
                
    $total getworkingdays_time($ENDSTAMP 86400, ($ENDSTAMP + ($total 86400) + 86400));
                
    $offset += $total;
            }
            unset(
    $holidaycounter$saturdaycounter$sundaycounter$i$noofdays$ts$total);
            return (
    $offset);
        }

        function 
    check_holiday_range($STARTSTAMP$ENDSTAMP){
            @
    sqlconnect(); // not a sql connection! ;)
            
    $query "SELECT COUNT(*) AS count FROM public_holidays WHERE `date` >= FROM_UNIXTIME(".$STARTSTAMP.") AND `date` <= FROM_UNIXTIME(".$ENDSTAMP.")";
            
    $sql mysql_query($query) or sqlerrorhandler("(".mysql_errno().") ".mysql_error(), $query$_SERVER['PHP_SELF'], __LINE__);
            
    $result mysql_fetch_array($sql);
            @
    mysql_free_result($sql);
            return 
    $result['count'];
        } 
    Matthew Bagley
    Paramiliar Design Studios
    IT Consultant | Website Design | Website Development

  9. #9
    Jedi Master Thor Erik is on a distinguished road Thor Erik's Avatar
    Join Date
    January 8, 2008
    Location
    <.< not in oslo soon
    Posts
    33
    Rep Power
    5
    Feedback Score
    0

    Default

    Quote Originally Posted by Paramiliar View Post
    here is the code

    if anyone wants me to post the check_holiday_range() function let me know but all it does is check a database with the timestamp range and gets the number of rows

    PHP Code:
    /*
    **    Function     :    getworkingdays_time
    **    Attributes    :    $STARTSTAMP = timestamp of the start day
    **                :    $ENDSTAMP = timestamp of the end day
    **    Description    :    returns the number of extra working days to be added
    **                    worked out by adding the number of bank holidays, 
    **                    the number of saturdays they do not work and
    **                    the number of sundays they do not work.
    */
        
    function getworkingdays_time($STARTSTAMP$ENDSTAMP){
            
    $noofdays ceil(($ENDSTAMP $STARTSTAMP) / 86400);
            
    $sundaycounter 0;
            
    $saturdaycounter 0;
            
    $holidaycounter 0;
            
    $offset 0;
            
    $holidaycounter check_holiday_range($STARTSTAMP$ENDSTAMP);        // check holiday range
            
            
    for ($i 0$i <= $noofdays$i++){
                
    $ts $STARTSTAMP + ($i 86400);
                if (
    WORKSATURDAYS == '0' && date("l"$ts) == "Saturday"){
                    
    ## they dont work saturdays
                    
    $saturdaycounter ++;
                } elseif (
    WORKSUNDAYS == '0' && date("l"$ts) == "Sunday"){
                    
    ## they dont work sundays
                    
    $sundaycounter ++;
                }        
            }
            
    $total $holidaycounter $saturdaycounter $sundaycounter;
            
    $offset $total;
            if (
    $total 0){
                
    $total getworkingdays_time($ENDSTAMP 86400, ($ENDSTAMP + ($total 86400) + 86400));
                
    $offset += $total;
            }
            unset(
    $holidaycounter$saturdaycounter$sundaycounter$i$noofdays$ts$total);
            return (
    $offset);
        }

        function 
    check_holiday_range($STARTSTAMP$ENDSTAMP){
            @
    sqlconnect(); // not a sql connection! ;)
            
    $query "SELECT COUNT(*) AS count FROM public_holidays WHERE `date` >= FROM_UNIXTIME(".$STARTSTAMP.") AND `date` <= FROM_UNIXTIME(".$ENDSTAMP.")";
            
    $sql mysql_query($query) or sqlerrorhandler("(".mysql_errno().") ".mysql_error(), $query$_SERVER['PHP_SELF'], __LINE__);
            
    $result mysql_fetch_array($sql);
            @
    mysql_free_result($sql);
            return 
    $result['count'];
        } 
    add this to the top of the function:
    PHP Code:
    if(!defined("WORKSATURDAYS"))
    {
        
    define("WORKSATURDAYS"0);
    }
    if(!
    defined("WORKSUNDAYS"))
    {
        
    define("WORKSUNDAYS"0);

    else you might want to change this:
    PHP Code:
                if (WORKSATURDAYS == '0' && date("l"$ts) == "Saturday"){

                    
    ## they dont work saturdays

                    
    $saturdaycounter ++;

                } elseif (
    WORKSUNDAYS == '0' && date("l"$ts) == "Sunday"){

                    
    ## they dont work sundays

                    
    $sundaycounter ++;

                } 
    to
    PHP Code:
                if (WORKSATURDAYS == '0' && date("l"$ts) == "Saturday"){

                    
    ## they dont work saturdays

                    
    $saturdaycounter ++;

                } 
    if (
    WORKSUNDAYS == '0' && date("l"$ts) == "Sunday"){

                    
    ## they dont work sundays

                    
    $sundaycounter ++;

                } 
    This way, you can check both, the old way, it would return true on saturday, and even if you had true on sundays too, it would't be registrated

  10. #10
    Jedi Master Paramiliar is on a distinguished road Paramiliar's Avatar
    Join Date
    July 24, 2007
    Location
    West Midlands
    Posts
    105
    Rep Power
    5
    Feedback Score
    0

    Default

    those constants are set in a global file included with every script hence the reason they are not set in the function code.
    Matthew Bagley
    Paramiliar Design Studios
    IT Consultant | Website Design | Website Development

  11. #11
    Jedi Master Thor Erik is on a distinguished road Thor Erik's Avatar
    Join Date
    January 8, 2008
    Location
    <.< not in oslo soon
    Posts
    33
    Rep Power
    5
    Feedback Score
    0

    Default

    Quote Originally Posted by Paramiliar View Post
    those constants are set in a global file included with every script hence the reason they are not set in the function code.
    Ah, but for others to use it, it might be an idea to have it there, just incase :stongue:

Closed Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

     

Similar Threads

  1. Wow! Google has me number two!
    By iowadawg in forum Google
    Replies: 22
    Last Post: Dec 8th, 2010, 1:43 am
  2. Get your number now!
    By iowadawg in forum Forum Lounge
    Replies: 18
    Last Post: May 9th, 2008, 8:52 pm
  3. How can i retrieve my posts...
    By danger9918 in forum General Business
    Replies: 3
    Last Post: Mar 27th, 2008, 2:06 pm
  4. Ranking Number 1 For Keywords?
    By dgridley in forum SEO Forum
    Replies: 10
    Last Post: Oct 5th, 2007, 1:29 pm

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
WebTalkForums
WebTalkForums
Recent Forum Threads