2014-03-06 143 views
0

我有一個帶有2個輸入文本(開始&結束)的表單,都使用jQuery數據閱讀器。 使用jQuery我特林得到天落於日期(每年兩個學期)的預定範圍的數量適用不同的費率jQuery日期範圍內的天數

For ex: 

     start-date end-date  rate 

Range A: 01/01/2012 - 06/30/2012 --> 5% 
Range B: 07/01/2012 - 12/31/2012 --> 10% 
Range C: 01/01/2013 - 06/30/2013 --> 15% 
Range D: 07/01/2013 - 12/31/2013 --> 20% 
and so on... 

So if date inserted in "start" is = 08/15/2012 
and the date inserted in "end" is = 11/20/2013 

The number of days per range are: 
Range A: 0 
Range B: 138 with a rate 10% 
Range C: 181 with a rate 15% 
Range D: 143 with a rate 20% 

因此,答案是,如何做這樣的事情:

(Math.min(end,rangeX_end-date) - Math.max(start,rangeX_start-date))*rangeX_rate 

回答

1

這裏是一個函數,這將幫助你.. 它的用法相同的SQL ..

function datediff(fromDate,toDate,interval) { 
      var second=1000, minute=second*60, hour=minute*60, day=hour*24, week=day*7; 
      fromDate = new Date(fromDate); 
      toDate = new Date(toDate); 
      var timediff = toDate - fromDate; 
      if (isNaN(timediff)) return NaN; 
      switch (interval) { 
       case "years": return toDate.getFullYear() - fromDate.getFullYear(); 
       case "months": return ( 
        (toDate.getFullYear() * 12 + toDate.getMonth()) 
        - 
        (fromDate.getFullYear() * 12 + fromDate.getMonth()) 
       ); 
       case "weeks" : return Math.floor(timediff/week); 
       case "days" : return Math.floor(timediff/day); 
       case "hours" : return Math.floor(timediff/hour); 
       case "minutes": return Math.floor(timediff/minute); 
       case "seconds": return Math.floor(timediff/second); 
       default: return undefined; 
      } 
     } 

向下滾動更新的提琴在這裏看到「整潔」版本; http://jsfiddle.net/uUqrT/5/

$("#calc").click(function() 
{ 
    addDaysRow($('#from').val(), $('#to').val()); 
}); 

function addDaysRow(fromDate, toDate) { 
    var rangeAstart = new Date('01/01/2012'); 
    var rangeAend = new Date('06/30/2012'); 
    var rangeBstart = new Date('07/01/2012'); 
    var rangeBend = new Date('12/31/2012'); 
    var rangeCstart = new Date('01/01/2013'); 
    var rangeCend = new Date('06/30/2013'); 
    var rangeDstart = new Date('07/01/2013'); 
    var rangeDend = new Date('12/31/2013'); 

    var diff = datediff(fromDate, toDate, "days"); 

    $('#record > tbody:last').append('<tr><td>' + diff + '</td><td>' + diff + '</td><td>' +diff + '</td><td>' + diff + '</td><td>' + diff + '</td><td>' + diff + '</td><td>' + diff + '</td></tr>'); 
} 

這應該在正確的軌道上開始你 - 不知道你想在這裏與範圍內做什麼。

+0

DATEDIFF('10/10/2010' ,'20/12/2010' , '天' ); –

+0

這個函數計算兩個日期之間的天數,感謝這個。但如何計算谷底所有區間的天數?例如:返回範圍A中的天數,比範圍B中的天數,範圍內的C等...我有50個範圍或多或少,我必須使50 var?有沒有辦法使用循環?謝謝 – fasenderos

+0

是的,你在做什麼?你可以在JSFiddle中做一個模型,並告訴我你需要什麼功能以及在哪裏?然後我會填寫代碼。 @fasenderos –

1

你不需要jQuery的它,請參閱附件的jsfiddle

var start = new Date('2011-04-11'); 
var end = new Date('2012-04-11'); 
var diff = Math.round((end- start)/(1000*60*60*24)); 

http://jsfiddle.net/4t7DU/

相關問題