0

I have this JS Code:

$("#submit").on('click',function() {
    //work out number of days between the two dates
    var days_between = $("#todate").val() - $("#fromdate").val()

    //do the cost per month times 12 (months)
    var year_cost = $("#cost_per_month").val() * 12

    //do the yearly cost / 365
    var daily_cost = year_cost / 365
    var daily_cost = parseFloat( daily_cost.toFixed(2) )

    //now do the daily cost times cost_per_month
    var total_cost = daily_cost * days_between

    $(".total_days").html(days_between);
    $(".total_cost").html(total_cost);
})

I am getting an error saying NaN though.

i am entering the following:

#from_date = 2014-08-19
#to_date = 2014-08-31
#cost_per_month = 2.60
user3843997
  • 205
  • 1
  • 5
  • 9
  • 3
    Not suprisingly, `"2014-08-19" - "2014-08-31"` is not a number ? – adeneo Aug 22 '14 at 10:21
  • are IDs 'fromdate' 'todate' or 'from_date' 'to_date' – Luca B. Aug 22 '14 at 10:22
  • It would be useful to know if you're using a datepicker or just typing the dates. If you're using something like jQuery's datepicker it would give you totally different answers. – adeneo Aug 22 '14 at 10:31

4 Answers4

2

The way you are calculating number of dayes between the dats is wrong. look into this How do I get the number of days between two dates in JavaScript? This could be helpful!

Community
  • 1
  • 1
Navaneeth
  • 2,555
  • 1
  • 18
  • 38
1

This Will Work

    //work out number of days between the two dates
var oneDay = 24 * 60 * 60 * 1000; 
//var date1 = new Date("2014,08,31");
//var date2 = new Date("2014,08,19");

var date1 = new Date("2014-08-31");
var date2 = new Date("2014-08-19");

var Daysd = date1.getDate() - date2.getDate();

    //var days_between = date1 - date2
    var diffDays = Math.round(Math.abs((date1.getTime() - date2.getTime()) / (oneDay)));

    //do the cost per month times 12 (months)
    var year_cost = parseInt(2.60) * 12

alert(Daysd);
alert(year_cost);

DEMO

cracker
  • 4,900
  • 3
  • 23
  • 41
0

you can't get total days directly

   var tDate = new Date($("#todate").val());
    var fDate = new Date($("#fromdate").val());
    var diff=tDate-fDate;

    This would give you the difference in milliseconds between the two dates.

    var DaysNo= diff / 1000 / 60 / 60 / 24;
Amit Kumar
  • 5,888
  • 11
  • 47
  • 85
-1

You have not parsed textbox values to int:

var days_between = parseInt($("#todate").val()) - parseInt($("#fromdate").val())

and

var year_cost = parseInt($("#cost_per_month").val()) * 12
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125