2016-08-08 30 views
1

ユーザが日付を入れた場合 08/08/2016から08/09/2016 = 1月 08/08/2016から01/09/2016 = 1ヶ月 でも 2016年8月8日30/08/2016に= 1ヶ月Jqueryで2つの日付の間の月を計算する

のでbasicly誰かが2016年1月8日から1ヶ月としてカウント30/08/2016に部屋を借りたい場合

誰でも私がjqueryでこれを達成するのを助けることができますか?

どこから始めましょうか。

+1

[moment.js](http://momentjs.com/) – Andreas

+0

は、私はそれをやってのけるために管理することができた場合、それに見に行く、よさそうです。ありがとうございました! –

答えて

0

このコードをご覧ください。

これはテスト中です。日付を「MM/DD/YYYY」形式、すなわち米国の日付形式で入力します。私は、それはあなた、あなたがこの非常に単純な方法を行うことができますmoment.jsを使用

$(document).ready(function() { 
 
    $("#calc").click(function() { 
 
    var from = $("#from").val(); 
 
    var to = $("#to").val(); 
 
    var monthDifference = 0; 
 
    if (from != "" && to != "") { 
 
     var fromDate = new Date(from); 
 
     var toDate = new Date(to); 
 
     calculateMonths(fromDate, toDate, monthDifference); 
 
    } 
 
    }); 
 

 
    function calculateMonths(fromDate, toDate, monthDifference) { 
 

 
    if (fromDate < toDate) { 
 
     monthDifference++; 
 
     fromDate.setMonth(fromDate.getMonth() + 1); 
 
     calculateMonths(fromDate, toDate, monthDifference); 
 
    } else 
 
     alert("monthDifference "+monthDifference); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
 
From: 
 
<input type="text" id="from" value="08/08/2016"/>To: 
 
<input type="text" id="to" value="10/08/2016"/> 
 

 
<br/> 
 
<br/> 
 
<button id="calc">Calculate</button>

+0

ようこそ@JeffreyLang .... ':)'! – vijayP

0

役立つことを願っています。あなたはmoment.jsファイルをインポートする必要があります。

// 31 Oct 2013 - 1 Feb 2014 
> moment([2014, 1, 1]).diff(moment([2013, 9, 31]), 'months', true) 
2.983050847457627 

// 31 Oct 2013 - 31 Jan 2014 
> moment([2014, 0, 31]).diff(moment([2013, 9, 31]), 'months', true) 
3 

// 31 Oct 2013 - 30 Jan 2014 
> moment([2014, 0, 30]).diff(moment([2013, 9, 31]), 'months', true) 
2.967741935483871 
関連する問題