Weekday difference between two given days

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • RamananKalirajan
    Contributor
    • Mar 2008
    • 608

    Weekday difference between two given days

    Can any one please help me out in calculating the no of weekdays between two givendays using Javascripts I tried in many way but I cant get the solution. The date format I am using is DD-MON-YYYY. Please help me out
  • RamananKalirajan
    Contributor
    • Mar 2008
    • 608

    #2
    Find Weekday between two dates

    Hello firends, here i give a code that finds the weekday between two dates. But the problem is the code just subtracts only two days (i.e. a saturday and Sunday). can any one please solve this.

    The Code:

    [HTML]<html>
    <head>
    <script language="javas cript">
    function diffDate()
    {
    var day1, day2;
    var month1, month2;
    var year1, year2;

    value1 = document.getEle mentById('stDat e').value;
    value2 = document.getEle mentById('endDa te').value;

    day1 = value1.substrin g (0, value1.indexOf ("-"));
    month1 = value1.substrin g (value1.indexOf ("-")+1, value1.lastInde xOf ("-"));
    year1 = value1.substrin g (value1.lastInd exOf ("-")+1, value1.length);

    day2 = value2.substrin g (0, value2.indexOf ("-"));
    month2 = value2.substrin g (value2.indexOf ("-")+1, value2.lastInde xOf ("-"));
    year2 = value2.substrin g (value2.lastInd exOf ("-")+1, value2.length);

    date1 = year1+"/"+month1+"/"+day1;
    date2 = year2+"/"+month2+"/"+day2;

    firstDate = Date.parse(date 1);
    secondDate= Date.parse(date 2);

    var ddate1 = new Date();
    var ddate2 = new Date();

    ddate1.setUTCMi lliseconds(firs tDate);
    ddate2.setUTCMi lliseconds(seco ndDate);

    var msPerDay = 24 * 60 * 60 * 1000
    var dbd = Math.round((sec ondDate.valueOf ()-firstDate.value Of())/ msPerDay)+1;
    alert(dbd);

    var iWeeks, iDateDiff, iAdjust = 0;
    var iWeekday1 = ddate1.getDay() ; // day of week
    var iWeekday2 = ddate2.getDay() ;
    iWeekday1 = (iWeekday1 == 0) ? 7 : iWeekday1; // change Sunday from 0 to 7
    iWeekday2 = (iWeekday2 == 0) ? 7 : iWeekday2;
    if ((iWeekday1 > 5) && (iWeekday2 > 5))
    iAdjust = 1; // adjustment if both days on weekend
    iWeekday1 = (iWeekday1 > 5) ? 5 : iWeekday1; // only count weekdays
    iWeekday2 = (iWeekday2 > 5) ? 5 : iWeekday2; // calculate differnece in weeks (1000mS * 60sec * 60min * 24hrs * 7 days = 604800000)
    iWeeks = Math.floor((dda te2.getTime() - ddate1.getTime( )) / 604800000);
    if (iWeekday1 <= iWeekday2)
    {
    iDateDiff = (iWeeks * 5) + (iWeekday2 - iWeekday1)
    }
    else
    {
    iDateDiff = ((iWeeks + 1) * 5) - (iWeekday1 - iWeekday2)
    }

    iDateDiff -= iAdjust // take into account both days on weekend
    iDateDiff =iDateDiff +1;
    alert("The Working Days are "+iDateDiff );
    }
    </script>
    </head>
    <body>
    <input type="text" id="stDate"><b r/>
    <input type="text" id="endDate"><b r/>
    <input type="button" value="calculat e" onclick="diffDa te()">
    </body>
    </html>
    [/HTML]
    Please Help Me out
    Last edited by acoder; Mar 10 '08, 03:14 PM. Reason: Added code tags

    Comment

    • acoder
      Recognized Expert MVP
      • Nov 2006
      • 16032

      #3
      Threads merged. Please do not double post.

      Also remember to use [code] tags when posting code.

      Comment

      • mrhoo
        Contributor
        • Jun 2006
        • 428

        #4
        /*
        Date calculations from user input can be tricky-
        the safest method is to have your visitor choose from a calendar or
        a set of drop downs. If you let them type in their own dates,
        make sure you have actual dates to work with before you use them.

        I simplified your code here, but to pay for it
        you will need to come up with a Holidays object on your own-
        you need to subtract week-day holidays from the business days total.
        (I made it optional here, but you will need it for accurate business day counts)
        The particular holidays depend on the business.
        Lucky for you that Easter always falls on a Sunday....

        I made it a method of the Date object, but you can make it a method of
        any object you have handy, or even a global function- whatever works.
        */
        [CODE=javascript]Date.bizDays= function(d1,d2, skipholidays){
        d1= Date.fromInput( d1);
        d2= Date.fromInput( d2);

        var wd1= d1.getDay();
        var wd2= d2.getDay();

        var interval= Math.abs(d1-d2);
        var days= Math.floor(inte rval/8.46e7);
        var tem= days%7;
        var weeks= Math.floor(days/7);
        if(wd1== 6) tem-= 2;
        else if(wd1== 0) tem-= 1;
        if(wd2== 0) tem-= 1;

        if(skipholidays === true && Holidays=== 'object'){
        var skip= new Holidays(d1,d2) .length;
        tem-= skip;
        }
        return weeks*5+tem;
        }[/CODE]
        [CODE=javascript]
        Date.fromInput= function(d){
        try{
        if(typeof d== 'number')d=new Date(d);
        if(typeof d== 'string') d= new Date(Date.parse (d));
        if(d.getDay()) return d;
        }
        catch(er){
        throw('Bad Date!')
        }
        }[/CODE]
        //test - the format of the string depends on the OS language settings
        //you can pass actual Date Objects, or time stamps as well as strings
        alert(Date.bizD ays('March 11, 2008','April 15,2008')+' business days');
        //error test
        //Date.bizDays()

        Comment

        • RamananKalirajan
          Contributor
          • Mar 2008
          • 608

          #5
          Originally posted by mrhoo
          /*
          Date calculations from user input can be tricky-
          the safest method is to have your visitor choose from a calendar or
          a set of drop downs. If you let them type in their own dates,
          make sure you have actual dates to work with before you use them.

          I simplified your code here, but to pay for it
          you will need to come up with a Holidays object on your own-
          you need to subtract week-day holidays from the business days total.
          (I made it optional here, but you will need it for accurate business day counts)
          The particular holidays depend on the business.
          Lucky for you that Easter always falls on a Sunday....

          I made it a method of the Date object, but you can make it a method of
          any object you have handy, or even a global function- whatever works.
          */
          [CODE=javascript]Date.bizDays= function(d1,d2, skipholidays){
          d1= Date.fromInput( d1);
          d2= Date.fromInput( d2);

          var wd1= d1.getDay();
          var wd2= d2.getDay();

          var interval= Math.abs(d1-d2);
          var days= Math.floor(inte rval/8.46e7);
          var tem= days%7;
          var weeks= Math.floor(days/7);
          if(wd1== 6) tem-= 2;
          else if(wd1== 0) tem-= 1;
          if(wd2== 0) tem-= 1;

          if(skipholidays === true && Holidays=== 'object'){
          var skip= new Holidays(d1,d2) .length;
          tem-= skip;
          }
          return weeks*5+tem;
          }[/CODE]
          [CODE=javascript]
          Date.fromInput= function(d){
          try{
          if(typeof d== 'number')d=new Date(d);
          if(typeof d== 'string') d= new Date(Date.parse (d));
          if(d.getDay()) return d;
          }
          catch(er){
          throw('Bad Date!')
          }
          }[/CODE]
          //test - the format of the string depends on the OS language settings
          //you can pass actual Date Objects, or time stamps as well as strings
          alert(Date.bizD ays('March 11, 2008','April 15,2008')+' business days');
          //error test
          //Date.bizDays()

          Thank You Sir, But i found another way to do this that was pretty cool I tried it and it is working well but it will take more time for high date difference. The following is the code

          Code:
          <Html>
          <head>
          <script language="javascript">
          function changeVal(month)
          {
          if(month=="jan"||month=="Jan"||month=="JAN")
                month=0;
          if(month=="feb"||month=="Feb"||month=="FEB")
                month=1;
          if(month=="mar"||month=="Mar"||month=="MAR")
                month=2;
          if(month=="apr"||month=="Apr"||month=="APR")
                month=3;
          if(month=="may"||month=="May"||month=="MAY")
                month=4;
          if(month=="jun"||month=="Jun"||month=="JUN")
                month=5;
          if(month=="jul"||month=="Jul"||month=="JUL")
                month=6;
          if(month=="aug"||month=="Aug"||month=="AUG")
                month=7;
          if(month=="sep"||month=="Sep"||month=="SEP")
                month=8;
          if(month=="oct"||month=="Oct"||month=="OCT")
                month=9;
          if(month=="nov"||month=="Nov"||month=="NOV")
                month=10;
          if(month=="dec"||month=="Dec"||month=="DEC")
                month=11;
          
          return(month);
          }
          function findDiff()
          {
          var day1, day2;
          var month1, month2;
          var year1, year2;
          
          value1 = document.getElementById('stDate').value;
          value2 = document.getElementById('endDate').value;
          
          day1 = value1.substring (0, value1.indexOf ("-"));
          month1 = value1.substring (value1.indexOf ("-")+1, value1.lastIndexOf ("-"));
          month1 = changeVal(month1);
          year1 = value1.substring (value1.lastIndexOf ("-")+1, value1.length);
          
          day2 = value2.substring (0, value2.indexOf ("-"));
          month2 = value2.substring (value2.indexOf ("-")+1, value2.lastIndexOf ("-"));
          month2 = changeVal(month2);
          year2 = value2.substring (value2.lastIndexOf ("-")+1, value2.length); 
          
          var startDate = new Date(year1,month1,day1);
          var endDate = new Date(year2,month2,day2);
          var wrkdays=0;
          
          while(startDate.getTime()<=endDate.getTime())
          {
               wrkdays++;	   
              if(startDate.getDay()==0)
             {
          	wrkdays--;
             }
             else if(startDate.getDay()==6)
            {
          	wrkdays--;
            }
            else
            {
            }
                var d = new Date(startDate.getTime() + 86400000);
             startDate=d;
          }
                alert("Total Workdays = "+wrkdays);
          }
          
          </script>
          </head>
          <body>
          <input type="text" id="stDate"><br/>
          <input type="text" id="endDate"><br/>
          <input type="button" value="calculate" onclick="findDiff()">
          </body>
          </html>
          Anyhow thank you for your reply. i will try that too. Thank you

          Comment

          • acoder
            Recognized Expert MVP
            • Nov 2006
            • 16032

            #6
            Originally posted by RamananKaliraja n
            Thank You Sir, But i found another way to do this that was pretty cool I tried it and it is working well but it will take more time for high date difference. The following is the code
            It can definitely be improved, e.g. the ChangeVal() function can be three/four lines:
            [code=javascript]function ChangeVal(month ) {
            var months = ["JAN","FEB","MA R",...,"DEC"];
            for (i = 0; i < months.length; i++) {
            if (month.toUpperC ase() == months[i]) return i;
            }
            return -1;
            }[/code]

            Comment

            • RamananKalirajan
              Contributor
              • Mar 2008
              • 608

              #7
              Originally posted by acoder
              It can definitely be improved, e.g. the ChangeVal() function can be three/four lines:
              [code=javascript]function ChangeVal(month ) {
              var months = ["JAN","FEB","MA R",...,"DEC"];
              for (i = 0; i < months.length; i++) {
              if (month.toUpperC ase() == months[i]) return i;
              }
              return -1;
              }[/code]

              Thank you for your suggestion sir I will make use of it
              Regards
              Ramanan

              Comment

              Working...