JQuery DateTimePicker UI获取两个datetimepickers之间的总天数
我想从我得到的两个定制的DateTimePickers获得总天数。
我试过这个function:
function dateDifference() { if($("#fradato").val()!='' && $("#fradato").val()!='') { var diff = ($("#fradato").datepicker("getDate") - $("#tildato").datepicker("getDate")) / 1000 / 60 / 60 / 24; $("#antalldager").val(diff)
我遇到的问题是,无论我在哪里尝试调用此函数,DateTimePicker都会停止工作。 那么我应该在哪里/如何调用此函数或者有更好的方法来执行此操作?
我想在这个文本框中显示toal days:
这是我的HTML:
valgavdato()
JS:
$( function valgavdato() { var dateFormat = "mm/dd/yy", to_MaxDate = 13; // From date + this = to maxDate from = $( "#fradato" ) .datepicker({ minDate: '0+', defaultDate: "+1w", changeMonth: true, numberOfMonths: 1 }) .on( "change", function() { var PickedDate = getDate( this ); // See that date is in UTC format. console.log( "From DatePicker: "+JSON.stringify(PickedDate) ); // Process the picked date. var tempDay = PickedDate.getDate() + to_MaxDate; // Add a number of days to the picked date. var tempMonth = PickedDate.getMonth() + 1; // Because months are zero based. var tempYear = PickedDate.getYear() + 1900; // Because years are 1900 based console.log( "Temp date: "+ tempYear+"/"+tempMonth+"/"+tempDay +" --- It may look impossible... But Date() handles it."); // Create a date object in a UTC format. var newMaxDate = new Date(Date.UTC(tempYear, tempMonth-1, tempDay, 0, 0, 0)); console.log( "New max date: : "+ JSON.stringify(newMaxDate) ); // Set the minDate ans maxDate options. to.datepicker( "option", {"minDate": PickedDate, "maxDate": newMaxDate}); }), to = $( "#tildato" ).datepicker({ maxDate: '14+', defaultDate: "+1w", changeMonth: true, numberOfMonths: 1 }) .on( "change", function() { from.datepicker( "option", "maxDate", getDate( this ) ); }); function getDate( element ) { var date; try { date = $.datepicker.parseDate( dateFormat, element.value ); } catch( error ) { date = null; } return date; } } ); function dateDifference() { if($("#fradato").val()!='' && $("#fradato").val()!='') { var diff = ($("#fradato").datepicker("getDate") - $("#tildato").datepicker("getDate")) / 1000 / 60 / 60 / 24; $("#antalldager").val(diff) } }
我认为@JanisP建议很好。 你也可以做一个轻量级的function:
function dateDifference(start, end) { // Assume Start and End string format: dd/mm/yyyy var d1 = new Date(start); var d2 = new Date(end); // d2 - d1 gives result in milliseconds // calculate number of days by Math.abs((d2-d1)/86400000, as 24*3600*1000 = 86400000 return Math.abs((d2-d1)/86400000) }
在这里找到: jQuery UI Datepicker – 日期之间的天数
更新
从jQuery UI Datepicker中选择一个Date Range示例,我创建了这个工作示例: https : //jsfiddle.net/Twisty/r8wx6afk/
它仅在两个字段在change
事件期间都有日期时计算天数。
Interesting Posts
trentrichardson datetimepicker和timepicker不起作用
防止时间戳插件打开日历
沿着日期和时间滚动的Javascript滑块
使用datetimepicker在rails 4中重新加载页面后更改日期格式
DateTimePicker在jqGrid中不起作用。 但它在它之外工作
DateTimePicker时间选择器24小时但在12小时显示?
datetimepicker在点击外部时将日期设置为今天的日期
如何在datetimepicker中添加基于小时的最少天数?
Jquery datetimepicker – 提前1小时
如何在jQuery datetimepicker中获取utc时间