You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Bootstrap Datepicker计算两个日期的年、月、日差值

解决Bootstrap Datepicker日期间年、月、日差值计算问题

我明白你想要实现的功能——选好两个日期后自动计算并显示它们之间的年、月、日差值,之前的Stack Overflow示例可能太复杂了,我给你一个简单易懂的实现方案,直接整合到你现有的代码里就行。

首先,咱们需要一个准确计算日期差的函数,因为直接用原生Date的getTime()相减只能得到总天数,没办法直接拆分成年、月、日,得考虑每个月天数不同、闰年这些情况。这个函数会接收两个Date对象,返回包含年、月、日差值的对象:

function calculateDateDifference(fromDate, toDate) {
  let years = toDate.getFullYear() - fromDate.getFullYear();
  let months = toDate.getMonth() - fromDate.getMonth();
  let days = toDate.getDate() - fromDate.getDate();

  // 处理天数为负的情况:向前借一个月
  if (days < 0) {
    months--;
    // 借的这个月的天数,要根据fromDate的月份来算
    const lastMonthDate = new Date(fromDate.getFullYear(), fromDate.getMonth(), 0);
    days += lastMonthDate.getDate();
  }

  // 处理月份为负的情况:向前借一年
  if (months < 0) {
    years--;
    months += 12;
  }

  return { years, months, days };
}

接下来,咱们把这个函数整合到你的现有代码里,还要添加触发计算的逻辑:当to-date选择完成后自动计算,同时当from-date改变清空to-date时,也要清空total-count。

修改后的完整JS代码如下:

$(function() {
  // 初始化from日期选择器
  $('#from-date').datepicker({
    autoclose: true,
    format: 'dd-mm-yyyy',
  }).on('changeDate', function(ev) {
    ConfigureToDate();
    // 清空总天数输入框
    $('#total-count').val('');
  });

  // 初始化to日期选择器,添加changeDate事件触发计算
  $('#to-date').datepicker({
    autoclose: true,
    format: 'dd-mm-yyyy',
    startDate: $('#from-date').val()
  }).on('changeDate', function(ev) {
    calculateAndDisplayDifference();
  });

  // 设置to日期的最小可选值
  function ConfigureToDate() {
    $('#to-date').val("").datepicker("update");
    $('#to-date').datepicker('setStartDate', $('#from-date').val());
  }

  // 计算并显示日期差值
  function calculateAndDisplayDifference() {
    const fromStr = $('#from-date').val();
    const toStr = $('#to-date').val();

    // 如果两个日期都没选,直接返回
    if (!fromStr || !toStr) return;

    // 把dd-mm-yyyy格式的字符串转成Date对象(注意月份要减1,因为原生Date是0开始的)
    const [fromDay, fromMonth, fromYear] = fromStr.split('-').map(Number);
    const [toDay, toMonth, toYear] = toStr.split('-').map(Number);
    const fromDate = new Date(fromYear, fromMonth - 1, fromDay);
    const toDate = new Date(toYear, toMonth - 1, toDay);

    // 调用计算函数
    const diff = calculateDateDifference(fromDate, toDate);

    // 格式化结果并显示到输入框
    const resultStr = `${diff.years} Year(s), ${diff.months} Month(s), ${diff.days} Day(s)`;
    $('#total-count').val(resultStr);
  }
});

关键说明:

  • 日期格式转换:因为Bootstrap Datepicker返回的是dd-mm-yyyy格式的字符串,而原生Date构造函数需要的是年, 月(0-11), 日,所以要拆分字符串并把月份减1。
  • 差值计算逻辑:先算年份差,再算月份差,最后算天数;如果天数/月份为负,就向前“借”一个月/一年,确保结果是正数。
  • 触发时机:在to-date选择完成后自动计算,同时当from-date改变时清空结果输入框,避免显示旧的错误数据。

你可以直接把这段代码替换掉你原来的JS部分,就能实现你想要的功能啦~

内容的提问来源于stack exchange,提问作者mvk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:28:30