Javascript添加/删除值

Javascript adding/removing values

本文关键字:删除 添加 Javascript      更新时间:2023-09-26

我有这个JS代码:

$("#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);
})

我得到一个错误说NaN虽然。

我正在输入以下内容:

#from_date = 2014-08-19
#to_date = 2014-08-31
#cost_per_month = 2.60

你计算日期之间天数的方法是错误的。看看这个如何在JavaScript中获得两个日期之间的天数?这可能会有帮助!

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);
演示

你不能直接得到总天数

   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;

您没有将文本框的值解析为int:

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

var year_cost = parseInt($("#cost_per_month").val()) * 12