2015-02-26 5 views
5

Sto provando a scrivere un programma che risolva la differenza tra due date utilizzando JavaScript. Le due date che voglio confrontare sono inserite usando un modulo HTML usando il formato della data. Voglio confrontare le due date immesse utilizzando javaScript, in particolare, per trovare la differenza tra le due date in settimane complete e quindi i giorni rimanenti. Sono riuscito a confrontare due date hardcoded in javaScript, ma sto avendo problemi a farlo con due date in una forma. Ogni consiglio sarebbe molto apprezzato! Di seguito si riporta il programma JavaScript:Conversione di data HTML dal modulo in JavaScript per confrontare due date.

<!DOCTYPE html> 
    <html> 
    <title> Dates </title> 
    <head>Class Test 

    <script language="javascript"> 
    function Ict5() { // ALERT BOX 
    today = new Date(); //Using new Date(), creates a new date object with the current date and time 

    birthday = new Date("March 28, 1995"); //using new date with stuff in the brackets, assigns the date to the variable 
    birthday.setFullYear(1995); 
    msPerDay = 24 * 60 * 60 * 1000; 
    msPerWeek = 7 * 24 * 60 * 60 * 1000; 
    msBetween = (today.getTime() - birthday.getTime()); //get time Returns the number of milliseconds since midnight Jan 1, 1970 
    daysBetween = Math.round(msBetween/msPerDay); //math round returns the value of a number rounded to the nearest integer. 
    weeksBetween = Math.floor(msBetween/msPerWeek); 
    window.alert("There are " +daysBetween+ " days or " +weeksBetween+ " full weeks between my date of birth and today "); 
    } 
    </script> 
    </head> 
    <body> 

    <H1> An Example of Form </H1> 



<Form action="process.pl" method="POST" name="MyForm" onsubmit="return formValidation()"> 

      <p>Enter Date:</p> 
      <input type=date name="date1" id="date1"> 
      <input type=date name="date2" id="date2"> 
<button type="button" onclick="Ict5()">Calculate Fare</button><br> 

    </Form>   


</body> 

</html> 
+1

Utilizzare la parola chiave var per rendere le variabili locali con ambito 'var msPerDay = ...' – andlrc

+0

vedere http://stackoverflow.com/a/35847982/5314529 –

risposta

0

È possibile ottenere il valore dagli ingressi come questo:

var date1 = new Date(document.getElementById("date1").value); 
1

Si potrebbe ottenere questo risultato utilizzando il moment.js library in particolare la manipulation methods. Una volta che lanci la data di JS in un oggetto di momento puoi interrogare moment.week() e ottenere il numero che stai cercando.

var week1 = moment("2015-2-1").week(); var week2 = moment("2015-2-8").week(); var numOfWeeksInBetween = week2 - week1;