1

My code is supposed to subtract dates (enddate-startdate) but nothing's happening and can't figure out where the problem is.

 <script type="text/javascript">
        function subtractDate()
        {

            var sDate = Date.parse("<%=txtStartDate.Text%>");
            var eDate = Date.parse("<%=txtEndDate.Text%>");
            var resultDate = document.getElementById("<%=txtnumberOfDaysCovered.ClientID%>")
            if (document.getElementById(sDate) < document.getElementById(eDate)) {
                var timeDiff = eDate.Subtract(sDate);
                resultDate = Math.floor(timeDiff / (1000 * 60 * 60 * 24));


            }
        }
    </script>

I already tried to call it behind

    protected void txtStartDate_TextChanged(object sender, EventArgs e)
    {

       // SubtractDateStartDateChange();
        Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "subtractDate(this.Id)", true);
    }

    protected void txtEndDate_TextChanged(object sender, EventArgs e)
    {
        //SubtractDate();
        Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "subtractDate(this.Id)", true);
    }
XPRGMRX
  • 27
  • 5
  • please ignore the last sentence – XPRGMRX May 15 '18 at 07:45
  • You can [edit] your question. – Ry- May 15 '18 at 07:46
  • You don't do anything with the result that `subtractDate` calculates. Therefore nothing happens. – Richard May 15 '18 at 07:47
  • Nothing will happen as you are just calculation resultDate and not using it anywhere – PSK May 15 '18 at 07:47
  • What is the value returned by `"<%=txtStartDate.Text%>"`? Hopefully you're aware of the pitfalls of using the built-in parser, see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG May 15 '18 at 08:25
  • i'm using a date picker for my date values. @psk resultDate is just a textbox that suppose to have the timediff value converted into days(integer) – XPRGMRX May 16 '18 at 03:13
  • Sorry i'm new at javascript :3 – XPRGMRX May 16 '18 at 03:17

1 Answers1

2

Your passing subtractDate(this.Id) from the code behind part, But the function subtractDate() not expecting any parameter on the client side. I think, due to this the function is not working.function subtractDate() expecting an Id parameter, Change the function with a param.

Hope function as follows will work.

function subtractDate(var id)
        {

            var sDate = Date.parse("<%=txtStartDate.Text%>");
            var eDate = Date.parse("<%=txtEndDate.Text%>");
            var resultDate = document.getElementById("<%=txtnumberOfDaysCovered.ClientID%>")
            if (document.getElementById(sDate) < document.getElementById(eDate)) {
                var timeDiff = eDate.Subtract(sDate);
                resultDate = Math.floor(timeDiff / (1000 * 60 * 60 * 24));


            }
        }
vijesh
  • 1,115
  • 1
  • 11
  • 27