Jquery get total days from 2 inputs and display

2019-08-29 11:09发布

I have two inputs which take a date such as 11/04/2010 (im using a jquery datepicker)

I want to calculate and display the number of days between the two dates as well as the value of multiplying the total days with a set number i.e $130.

My following layout is like so where "5 days" and "$125" represent the results calculated:

<ol>
<li><label for="start-date">Start Date:</label>
<input name="start-date" id="start-date" class="date-pick dp-applied"></li>
<li><label for="end-date">End Date:</label><input name="end-date" id="end-date" class="date-pick"></li>
<li><label for="book_days">Days:</label><p>5 days</p></li>
<li><label for="book_price">Total Price:</label><p>$125</p></li>
</ol>

2条回答
看我几分像从前
2楼-- · 2019-08-29 11:51

Check out this fiddle: http://jsfiddle.net/timbuethe/hD25E/

<ol>
<li><label for="start-date">Start Date:</label>
<input name="start-date" id="start-date" class="date-pick dp-applied"></li>
<li><label for="end-date">End Date:</label><input name="end-date" id="end-date" class="date-pick"></li>
<li><label for="book_days">Days:</label><p id="book_days">5 days</p></li>
<li><label for="book_price">Total Price:</label><p id="book_price">$125</p></li>
</ol>

Note: I've added id attributes for "book_days" and "book_price"

$('#start-date, #end-date').change(function(){

    if($('#start-date').val() && $('#end-date').val()){

        var startDate = parseDate($('#start-date').val())
        var endDate = parseDate($('#end-date').val())
        var days = calcDaysBetween(startDate, endDate)
        var price = calcPrice(days)

        $('#book_days').html(days + " days")    
        $('#book_price').html("$" + price)
    }
});

function parseDate(s){
    // TODO locale specific parsing here, e.g. http://www.datejs.com/
    var parts = s.split('/')
    return new Date(parts[2], parts[0]-1, parts[1])
}

function calcDaysBetween(startDate, endDate){
    return (endDate-startDate)/(1000*60*60*24)
}

function calcPrice(days){
    return days * 5;
}
查看更多
Emotional °昔
3楼-- · 2019-08-29 11:51

try like this

function GetCost()
{
   var days=daydiff(parseDate($('#start-date').val()), parseDate($('#end-date').val()));

   var cost = days*130;

   return cost;  
}


function parseDate(str) {
    var mdy = str.split('/')
    return new Date(mdy[2], mdy[0]-1, mdy[1]);
}

function daydiff(first, second) {
    return (second-first)/(1000*60*60*24)
}

Please check the SO link

查看更多
登录 后发表回答