美好的一天,
从jQuery datepicker中选择日期后,我计算从现在到选定日期的天数有点麻烦。
我认为日期选择器正在更改选择日期的日期格式并导致计算出错但我无法弄清楚如何解决这个问题。我确信这是我,但我看不到树林,所以任何建议都会有所帮助。
以下是代码:
<input type="text" class="datepicker-calc" />
<input type="text" id="tbAddDays" />
$(document).ready(function () {
$(".datepicker-calc").datepicker({
dateFormat: "dd/mm/yy",
changeMonth: true,
changeYear: true,
onSelect: function (date, e) {
var expDate = new Date(date);
var date = e.selectedDay;
if (date < 10) {
date = ("0" + e.selectedDay)
}
var month = e.selectedMonth;
if (month < 10) {
month = ("0" + e.selectedMonth)
}
var year = e.selectedYear;
var endDate = month + "/" + date + "/" + year;
updateDays(endDate, e);
$(".datepicker-calc").datepicker("hide");
}
});
function treatAsUTC(date) {
var result = new Date(date);
result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
return result;
}
function updateDays(expDate, e) {
var now = new Date();
var startDate = now.toDateString('dd/MM/yyyy');
var exp = new Date(expDate);
var endDate = exp.toDateString('dd/MM/yyyy');
var millisecondsPerDay = 24 * 60 * 60 * 1000;
var totalDays = (treatAsUTC(endDate) - treatAsUTC(startDate)) / millisecondsPerDay;
$('#tbAddDays').val(totalDays);
}
});
答案 0 :(得分:2)
onSelect
事件将收到指定格式的字符串,即dd/mm/yy
。 JavaScript Date.parse
方法会错误地解析这些日期,或者根本不解析它们。解决方案是使用jQuery中构建的parseDate()
函数:
onSelect: function (dateText, inst) {
var expDate = $.datepicker.parseDate(inst.settings.dateFormat, dateText, inst.settings);
var diff = expDate - new Date();
var days = diff / 1000 / 60 / 60 / 24;
alert( /* ceil, floor, round */ days);
}
答案 1 :(得分:0)
意识到我需要显示为jQuery dd / mm / yy(dd / mm / yyyy)格式,所以保留了并对expDate做了一些操作,传递给updateDays()方法以确保日期为计算将由JS正确处理。
工作脚本:
$(".datepicker-calc").datepicker({
dateFormat: "dd/mm/yy",
changeMonth: true,
changeYear: true,
onSelect: function (selectdate, e) {
var newDate = selectdate.slice(0,2);
var newMonth = selectdate.slice(4,6);
if (newMonth < "10") { newMonth = ("0" + newMonth.slice(0,1));};
var newYear = selectdate.slice(6,11);
var expDate = newMonth + "/" + newDate + "/" + newYear;
updateDays(expDate, e);
$(".datepicker-calc").datepicker("hide");
}
});
function treatAsUTC(date) {
var result = new Date(date);
result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
return result;
}
function updateDays(expDate, e) {
var now = new Date();
var startDate = now.toDateString('dd/MM/yyyy');
var expire = new Date(expDate);
var endDate = expire.toDateString('dd/MM/yyyy');
var millisecondsPerDay = 24 * 60 * 60 * 1000;
var totalDays = (treatAsUTC(endDate) - treatAsUTC(startDate)) / millisecondsPerDay;
$('#tbAddDays').val(totalDays);
}