www.webdeveloper.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 22

Thread: Adding business days to current date

  1. #1
    Join Date
    Jan 2014
    Posts
    5

    Adding business days to current date

    I am having trouble figuring out how to get a script to add business days to the current date.
    I created a table for our sales team to use that is supposed to display the correct ship date for their customers order.
    I need to be able to calculate the business days and display it month/day/year.

    Any help with this would be very appreciated.

  2. #2
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,410
    It is better to show some attempt at solving the problem.
    However, you can get a start by googling for similar solutions and then modify...

    Consider: http://javascript.about.com/library/blbusdayadd.htm
    There are a ton of other solutions with and without JQuery involved.

    You did not specify, but have you considered business days that are holidays also?
    There are solutions for this, but it does complicate the process a bit.

  3. #3
    Join Date
    Oct 2010
    Location
    Versailles, France
    Posts
    1,270
    I have build this page for school holidays in France

    Its works with PHP, which load an existing file (the names are holidays2014.txt) or build a javascript for a new Year :
    Code:
    <?php
        
        header("Content-Type:text/javascript;charset=utf-8");
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
        header("Cache-Control: no-cache, must-revalidate");
        header("Pragma: no-cache");
    
        $cnt='';
        $anc=$_SERVER["QUERY_STRING"];
        if ($h = opendir('.')){
            while (false !== ($fln = readdir($h)) && !$cnt) {
               if (0<strpos($fln,$anc.'.txt')) {$cnt=file_get_contents($fln);break;}}}
       closedir($h);
       if (!$cnt){ $cnt=str_repeat("000000",61);
            /* jours feriés légaux :    1er janvier, 1er et 8 mai,    lundi Pâques, 
            lundi pentecôte, 14 juillet, 15 août, 1er novembre, 11 novembre et Noël */
            $cnt[0]=1;
            $cnt[date('z',easter_date($anc)+129600)]=1;
            $cnt[date('z',easter_date($anc)+38*86400+129600)]=1;
            $cnt[date('z',easter_date($anc)+49*86400+129600)]=1;
            $cnt[date('z',mktime(12,0,0,5,1,$anc))]=1;
            $cnt[date('z',mktime(12,0,0,5,8,$anc))]=1;
            $cnt[date('z',mktime(12,0,0,7,14,$anc))]=1;
            $cnt[date('z',mktime(12,0,0,8,15,$anc))]=1;
            $cnt[date('z',mktime(12,0,0,11,1,$anc))]=1;
            $cnt[date('z',mktime(12,0,0,11,11,$anc))]=1;
            $cnt[date('z',mktime(12,0,0,12,25,$anc))]=1;}    
       exit('var vcs="'.$cnt.'";'.chr(13).chr(10).'edtCal("'.$anc.'");');
    ?>
    The connected users have the option by clicking on a month or a day, with the ctrl key, change its nature (with a little cahnge on this page which use the Ajax call sndRqt).

  4. #4
    Join Date
    Jan 2014
    Posts
    5
    I appreciate this, however, I really need it to be javascript.
    Here is what I am using now:
    var date = new Date();
    var newdate = new Date(date);
    newdate.setDate(newdate.getDate() + 3);
    var nd = new Date (newdate);
    document.write(nd.toLocaleDateString("en-US"));

    I need to make this code add days according to a business week.
    Thank you for the help.

  5. #5
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    2,405
    I would use a loop with a counter variable, create a date object, extract the day of week from it with .getDay() and test it and if its a work day, increment the counter, test the counter to see if it has reached the number of desired work days, if not, use setDate on the date object to move it forward in time and repeate the test / loop

    When number of days has been reached, you will have your future date object to extract the date information you want.

    job done.

    I would imagine that this is a 10 or so line routine, may be max 15 lines.
    Yes, I know I'm about as subtle as being hit by a bus..(\\.\ Aug08)
    Yep... I say it like I see it, even if it is like a baseball bat in the nutz... (\\.\ Aug08)
    I want to leave this world the same way I came into it, Screaming, Incontinent & No memory!
    I laughed that hard I burst my colostomy bag... (\\.\ May03)
    Life for some is like a car accident... Mine is like a motorway pile up...

    Problems with Vista? :: Getting Cryptic wid it. :: The 'C' word! :: Whois?

  6. #6
    Join Date
    Jan 2014
    Posts
    5
    @jmrker,
    I have been googling like crazy, the problem is that JavaScript is not my strong suit at all. I have run across the above link I am just not sure how to implement that code in what I am doing. If you could provide some guidance it would be very helpful.

  7. #7
    Join Date
    Sep 2007
    Posts
    22
    Shaun, I am trying to accomplish the same thing.
    In VB we have a function var=dateadd('d',datestr,+1). Adds one day.

    I can't find an equivalent in JS.

  8. #8
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    2,405
    Try this...
    Code:
    <!-- by \\.\ @ http://www.webdeveloper.com/forum/showthread.php?289325-Adding-business-days-to-current-date  -->
    var businessDays = 7, counter = 0; // set to 1 to count from next business day
    while( businessDays>0 ){
    	var tmp = new Date();
    	tmp.setDate( tmp.getDate() + counter++ );
    	switch( tmp.getDay() ){
    			case 0: case 6: break;// sunday & saturday
    			default:
    				businessDays--;
    			}; 
    }
    The nuts and bolts...

    if you then use tmp.toUTCString(); it will return the date based on number of business days.

    Tested in Chrome and Firefox.
    Yes, I know I'm about as subtle as being hit by a bus..(\\.\ Aug08)
    Yep... I say it like I see it, even if it is like a baseball bat in the nutz... (\\.\ Aug08)
    I want to leave this world the same way I came into it, Screaming, Incontinent & No memory!
    I laughed that hard I burst my colostomy bag... (\\.\ May03)
    Life for some is like a car accident... Mine is like a motorway pile up...

    Problems with Vista? :: Getting Cryptic wid it. :: The 'C' word! :: Whois?

  9. #9
    Join Date
    Jan 2014
    Posts
    5
    I am not sure how to use tmp.toUTString();

  10. #10
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,410

    Lightbulb

    Quote Originally Posted by shaun.101 View Post
    @jmrker,
    I have been googling like crazy, the problem is that JavaScript is not my strong suit at all. I have run across the above link I am just not sure how to implement that code in what I am doing. If you could provide some guidance it would be very helpful.
    Another solution ...

    Code:
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    
    <title> HTML5 page </title>
    
    </head>
    <body>
    
    <pre id="fourWeeks"></pre>
    Add <input id="nDaysToAdd" value="7"> days<p>
    <button onclick="calcBusinessDay()"> Calculate </button>
    <div id="debug"</div>
    
    <script type="text/javascript">
    
    Date.prototype.addDays = function (days) { return new Date(this.getTime() + days*24*60*60*1000); }
    
    Date.prototype.addBusinessDays = function (days) { 
      var nd = new Date();
      var wkday = 0;
      var moreDays = true;
      while (moreDays) {
        nd = new Date(nd.getTime() + 1*24*60*60*1000); // add a day
        if ( (nd.getDay() > 0) && (nd.getDay() < 6) ) {
          wkday++; if (wkday >= days) { moreDays = false; }
        }
      }
      return nd;
    }
    
    var today = new Date();  // global variables
    
    // following is for demonstration purposes only
    window.onload = function() {
      var newday = today;
      var str = '';
      for (var i=0; i<31; i++) {
        newday = new Date(today.getFullYear(),today.getMonth(),(today.getDate()+i));
        str += newday.toDateString()+'\t  =>\t'+i+' actual days ahead<br>';
      }
      document.getElementById('fourWeeks').innerHTML = str;
    }
    
    function calcBusinessDay() {
      var today = new Date();
      var N = parseInt(document.getElementById('nDaysToAdd').value) || 0;
      
      var wd = today.addDays(N);
      document.getElementById('debug').innerHTML = '<p>'+N+' week days will be on: '+wd.toDateString();
    
      var bd = today.addBusinessDays(N);
      document.getElementById('debug').innerHTML += '<p>'+N+' business days will be on: '+bd.toDateString();
    
    }
    </script>
    
    </body>
    </html>

  11. #11
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    2,405
    Quote Originally Posted by shaun.101 View Post
    I am not sure how to use tmp.toUTString();
    x = tmp.toUTString();

    where x will be a variable that then contains the string for time and date.

    You only need to extract from tmp the details you want by other methods()

    If you don't understand how to then you should look it up by googling JavaScript Date object and looking at sites like W3 Schools
    Yes, I know I'm about as subtle as being hit by a bus..(\\.\ Aug08)
    Yep... I say it like I see it, even if it is like a baseball bat in the nutz... (\\.\ Aug08)
    I want to leave this world the same way I came into it, Screaming, Incontinent & No memory!
    I laughed that hard I burst my colostomy bag... (\\.\ May03)
    Life for some is like a car accident... Mine is like a motorway pile up...

    Problems with Vista? :: Getting Cryptic wid it. :: The 'C' word! :: Whois?

  12. #12
    I have written a small function for you

    function getBussinessDays(days){
    var cDate = new Date();
    for (var i = 1; i <= days ; i++){
    var counter = 1;
    cDate.setDate(cDate.getDate() + counter);
    if (cDate.getDay() == 6 || cDate.getDay() == 0) days++;
    }
    return cDate;
    }

    Pass days as parameter. For example

    document.write(getBussinessDays(10))

    will add 10 days excluding holidays

    This is my 1st post. Hope this will help

  13. #13
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,410

    Lightbulb

    More suggestions ...

    If you keep the functions a prototypes, you can default to the current day for the calculations
    OR pre-set the start date and add regular or business/holidays from that date.
    It makes for a more general purpose function rather than ALWAYS choosing the current date.

    If you want to exclude pre-defined holidays as part of your display, you could expand on the following functions.
    Code:
    var holidays = [  // format is [year,month,date] where month is 1..12 (not 0..11 as the Date() object defines.
       [2014,2,10], // faux holiday: Feb 10, 2014 for testing before holiday
       [2014,7,4],  // July 4, 2014
    ];
    // Date format for holidays could be the Date() object format, 
    // but would need to change the 'addBusAndHoliDays' function to remove the new Date() month initialization.
    
    Date.prototype.addDays = function (days) { return new Date(this.getTime() + days*24*60*60*1000); }
    
    Date.prototype.addBusAndHoliDays = function (days) {
      var cDate = this; 
      var holiday = new Date();
      var c='', h='';
      for (var i=1; i<=days ; i++){
        cDate.setDate(cDate.getDate() + 1);
        if (cDate.getDay() == 6 || cDate.getDay() == 0) { days++; }
    	else {
    	  for (j=0; j<holidays.length; j++) {
    	    holiday = new Date(holidays[j][0],(holidays[j][1]-1),holidays[j][2]);
    		c = cDate.toDateString();  h = holiday.toDateString();
    	    if (c == h) { days++; }
    	  }
    	}
      } return cDate;
    }
    A demonstration program with holidays defined as Feb 10 and July 4 or 2014 is below.
    You can alter the number of days ahead to see the effect on different starting dates.
    NOTE: Demonstration display developed on 1/24/2014, hence the faux holiday of 2/10/2014 for testing.
    Holiday array can be easily changed for testing purposes in the future.

    Code:
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    
    <title> Add Days and Holidays </title>
    
    </head>
    <body>
    
    <pre id="fourWeeks"></pre>
    Add <input id="nDaysToAdd" value="14"> days<p>
    <button onclick="calcBusinessDay()"> Calculate </button>
    <div id="debug"</div>
    
    <script type="text/javascript">
    
    var today = new Date();  // global variables
    var holidays = [
       [2014,2,10], // faux holiday: Feb 10, 2014 for testing before holiday
       [2014,7,4],  // July 4, 2014
    ];
    
    Date.prototype.addDays = function (days) { return new Date(this.getTime() + days*24*60*60*1000); }
    
    Date.prototype.addBusAndHoliDays = function (days) {
      var cDate = this; 
      var holiday = new Date();
      var c='', h='';
      for (var i=1; i<=days ; i++){
        cDate.setDate(cDate.getDate() + 1);
        if (cDate.getDay() == 6 || cDate.getDay() == 0) { days++; }
    	else {
    	  for (j=0; j<holidays.length; j++) {
    	    holiday = new Date(holidays[j][0],(holidays[j][1]-1),holidays[j][2]);
    		c = cDate.toDateString();  h = holiday.toDateString();
    	    if (c == h) { days++; }
    	  }
    	}
      } return cDate;
    }
    
    // following is for demonstration purposes only
    Date.prototype.DayList = function (daysToShow) {
      var td = this;
      if (daysToShow == undefined) { daysToShow = 31; }
    
      var str = '';
      for (var i=0; i<daysToShow; i++) {
        newday = new Date(td.getFullYear(),td.getMonth(),(td.getDate()+i));
        str += newday.toDateString()+'\t  =>\t'+i+' actual days ahead<br>';
      } return str;
    }
    
    window.onload = function() {
      var str = 'Day List from today (with holidays on Feb 10 and July 4, 2014)<p>'+today.DayList();
      document.getElementById('fourWeeks').innerHTML = 'Day List:<p>'+str;
    }
    
    function calcBusinessDay() {  // for purposes of testing functions
      var today = new Date();
      var N = parseInt(document.getElementById('nDaysToAdd').value) || 0;
      
      var wd = today.addDays(N);
      document.getElementById('debug').innerHTML 
        = '<p>'+N+' week days from today ('+today.toDateString() +') will be on: '+wd.toDateString();
    
      var bd = today.addBusAndHoliDays(N);
      document.getElementById('debug').innerHTML += '<p>'+N+' business days will be on: '+bd.toDateString();
    
      var str = '';
      var newDay = new Date(2014,6,1);
      str += '<hr>7 days after July, 1, 2014 with 4th as defined holiday';
      str += '<p>'+newDay.DayList(14);
      document.getElementById('debug').innerHTML += '<p>'+str;
      
      wd = newDay.addDays(7);
      document.getElementById('debug').innerHTML += '<p>7 week days from July 1st will be on: '+wd.toDateString();
    
      bd = newDay.addBusAndHoliDays(7);
      document.getElementById('debug').innerHTML += '<p>7 business days will be on: '+bd.toDateString();
    }
    </script>
    
    </body>
    </html>
    Last edited by JMRKER; 01-24-2014 at 11:24 PM.

  14. #14
    Join Date
    Oct 2010
    Location
    Versailles, France
    Posts
    1,270
    Do not forget that every day have no longer the same duration of 24*60*60*1000 = 86,400,000 milliseconds with daylight saving time !

    Then It would be better to write something like this :
    Code:
    Date.prototype.addDays = function (days) { var dt = new Date(this.getTime());dt.setDate(dt.getDate()+days);return dt}
    to avoid a few well hidden errors...

  15. #15
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,410
    Quote Originally Posted by 007Julien View Post
    Do not forget that every day have no longer the same duration of 24*60*60*1000 = 86,400,000 milliseconds with daylight saving time !

    Then It would be better to write something like this :
    Code:
    Date.prototype.addDays = function (days) { var dt = new Date(this.getTime());dt.setDate(dt.getDate()+days);return dt}
    to avoid a few well hidden errors...
    While I don't think (60*60*1000) milliseconds between friends is that important at 2am twice a year
    your point is well taken in the general sense.

Thread Information

Users Browsing this Thread

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

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles