how to tell the difference between startdatetime and enddatetime in javascript

advertisements

This question already has an answer here:

  • Get difference between 2 dates in JavaScript? [duplicate] 8 answers

I want to calculate the difference between startdatetime and enddatetime

here is my html code:

StartDate:<input size="16" type="text" placeholder="YYYY-MM-DD" id="from_date" name="from_date" value="">

Enddate:<input size="16" type="text" placeholder="YYYY-MM-DD" id="to_date" name="to_date" onchange="calservicedays();" value="">

StartDate:2013-09-07 11:09:40

Enddate:2013-09-08 11:15:50

Below is my javascript code

function calservicedays(){
    var start = $("#from_date").val();
    var startDate = new Date(start);
    var end = $("#to_date").val();
    var endDate = new Date(end);
    var startcom =  Date.parse(start);
    var endcom = Date.parse(end);
    var diff = Math.floor((endDate.getTime() - startDate.getTime()) / 86400000);
    if((startDate != null && endDate != null) && (start != '' && end != '')){
        if((startDate != null && endDate != null) && (start != '' && end != '') && (startcom < endcom)){
            var diff = Math.floor((endDate.getTime() - startDate.getTime()) / 86400000);
            if(diff != "")
              $("#service").val(diff);
        }else{
                alert("To Date cannot be less than or equal to From date");
                 $("#service").val('');
                return false;
            }
    }
 }

With this javascript code i am just getting the difference in days. I want difference in days as well as time.

Can anyone tell me what changes i have to make in my javascript code to get the difference of date and time.

Thanks


Using date objects it will be easy refer to this Date Nice Function

jsfiddle

var date1 = new Date("7/11/2010");
var date2 = new Date("12/12/2010");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
alert(diffDays);