0

i have 3 text fields in rails view

<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>

by selecting dates from pickadate. mt code in application.js is :

$('.datepicker).pickadate();

i want to calculate the days between dates. my calculate method is defined below:-

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);
 }

but it does not work properly there is something missing. i didn't get it. please help me. Thanks in advance.

4

3 回答 3

0

在处理这种日期操作时,我真的很喜欢http://momentjs.com/库。

您将专门使用该from()方法: http: //momentjs.com/docs/#/displaying/from/

于 2015-05-21T19:15:40.527 回答
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)); 

示例:jsfiddle

于 2015-05-22T10:51:22.770 回答
0

嗨,我是 ruby​​ on rails 的新手,jquery pickadate 函数对我来说很新。函数在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 更改方法中调用计算函数。根据要求,所有功能都运行良好。谢谢你的帮助。

于 2015-05-22T16:10:53.520 回答