0

** I cannot convert the user selected date by using getTime(). I am beginner in java script. I get the date from user as start and end time and should be able to parse them and get the difference between them. Is there is a ay to get the whole date and parse or we need to split the date? **

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
    <%@ page contentType="text/html;charset=windows-1252"%>
<html>

  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"/>
    <title>Test</title>
    <script type="text/javascript"  >



 function check_date(){
    var start_date=document.getElementsByName("Start_Date");
    var End_date=document.getElementsByName("End_Date");
    var startdate_2=start_date.item(0).value;
     alert(startdate_2.getTime());*crashes here*
   var diffDays = (End_date - startdate_2)/(24*3600*1000);
     if ( diffDays > 14 )
       {alert("You entrered invalid date. Please repeat again");
       return false;
       }
       else
       {alert ("Will Proceed ");
       return true;}
}



  </script>
  </head>
  <body>
   <form ENCTYPE="multipart/form-data" ACTION="servlet1" METHOD=GET>
    <center>
    <fieldset>
            <label for="Start_Date">Start_Date</label>
            <input type="date" id="Start_Date" name="Start_Date" > <br> </br>
            <label for="END_Date">END_Date</label>
            <input type="date"  name="End_Date" id="End_Date"> <br> </br>
              <input type="submit"  value="Submit" onclick="return check_date();"> </input>
    </fieldset>
    </center>
  </form>
  </body>
</html>

2 Answers2

0

the value property of Start_Date is still returned as a string, even though it is a date input. Therefore you need to convert it to a Date by wrapping it in new Date() before calling getTime().

Also as your inputs have ids set you can simplify things a little and just use document.getElementById:

function check_date() {

    // start_date and End_date now point straight at the correct boxes.
    var start_date = document.getElementById("Start_Date");
    var End_date = document.getElementById("End_Date");

    // convert both entries to a Date object from the string value
    var startdate_2 = new Date(start_date.value);
    var enddate_2 = new Date(End_date.value);

    alert(startdate_2.getTime());

    var diffDays = (enddate_2 - startdate_2)/(24*3600*1000);
    if ( diffDays > 14 )
    {
        alert("You entered an invalid date. Please repeat again");
        return false;
    }
    else
    {
        alert ("Will Proceed");
        return true;
    }
}

Working Fiddle

Rhumborl
  • 16,349
  • 4
  • 39
  • 45
0

You want to convert both of these strings into the Javascript Date Object. Take a look at this previous answer: Compare two dates with JavaScript

Community
  • 1
  • 1
Edward Coyle Jr.
  • 437
  • 2
  • 13