2015-05-21 54 views
0

選擇我有3個文本字段中導軌通過從pickadate選擇日期查看計算數量通過pickadate在jquery的

<div> 
<%= f.label :from_date %> 
<%= f.text_field :start_date, :class => 'datepicker' %> 
</div> 
<div> 
<%= f.label :to_date %> 
<%= f.text_field :end_date, :class => 'datepicker' %> 
</div> 
<div> 
<label>Days</label 
<%= f.text_field :days,:readonly => true %> 
</div> 

。在application.js中 MT代碼:

$('.datepicker).pickadate(); 

我想計算日期之間的天數。我的計算方法定義如下: -

function calculate() { 
var d1 = $('#startdate').pickadate('getDate'); 
var d2 = $('#enddate').pickadate('getDate'); 
var diff = 1; 
if (d1 && d2) { 
diff = diff + Math.floor((d2.getTime() - d1.getTime())/86400000); 
} 
$('#days').val(diff); 
} 

但它不能正常工作有一些缺失。我沒有得到它。請幫幫我。提前致謝。

+0

這個Q/A的可能重複http://stackoverflow.com/questions/542938/how-do-i-get-the-number-of-days-between-two-dates-in-javascript?answertab=有源#製表頂 –

回答

0

喜是相當新的給我。功能定義於amsul.ca/pickadate.js/

從閱讀本網站。我只是想實施我的解決方案。

$('#start_date').pickadate({ 
    format: 'dd/mm/yyyy', 
    selectMonths: true, 
    selectYears: 25 
    } 
    }); 
    $('#end_date').pickadate({ 
    format: 'dd/mm/yyyy', 
    selectMonths: true, 
    selectYears: 25 
    } 
    }); 

調用函數來計算沒有周末的天數。

var firstDay = new Date($('#leave_start_date').val()), 
     lastDay = new Date($('#leave_end_date').val()), 
     daysDiff = calcHolidays(firstDay,lastDay); 
    if (isNaN(daysDiff)) 
     $('#leave_days').val(""); 
    else 
     $('#leave_days').val(daysDiff); 
    } 

calcHolidays()函數定義如下。

function calcHolidays(dDate1, dDate2) { 
var weeks, dateDiff, weekDay1, weekDay2; 
if (dDate2 < dDate1) return -1; 
weekDay1 = dDate1.getDay(), 
weekDay2 = dDate2.getDay(); 
weeks = Math.floor((dDate2.getTime() - dDate1.getTime())/604800000); 
if (weekDay1 <= weekDay2) 
dateDiff = (weeks * 5) + (weekDay2 - weekDay1); 
else 
dateDiff = ((weeks + 1) * 5) - (weekDay1 - weekDay2); 
return (dateDiff + 1); 
} 

在.datepicker更改方法中調用函數。根據需求,所有功能都非常好。 thanx尋求幫助。

0

下面的代碼會給你兩個日期之間的差異。

Date.daysBetween = function(date1, date2) { 
    //Get 1 day in milliseconds 
    var one_day=1000*60*60*24; 

    // Convert both dates to milliseconds 
    var date1_ms = date1.getTime(); 
    var date2_ms = date2.getTime(); 

    // Calculate the difference in milliseconds 
    var difference_ms = date2_ms - date1_ms; 

    // Convert back to days and return 
    return Math.round(difference_ms/one_day); 
} 

d1 = new Date('2015/5/22'); 
console.log(d1); 
d2 = new Date('2015/6/12'); 

console.log(Date.daysBetween(d1, d2)); 

例如:我在上軌和jQuery pickadate功能紅寶石新jsfiddle