You need to enable JavaScript to run this app. 使用JS计算两个日期间天数并实现预订日历价格自动计算
优惠活动
大模型
产品
解决方案
定价
更多

使用JS计算两个日期间天数并实现预订日历价格自动计算

实现方案

前置准备

首先需要在页面中新增一个展示总价格的DOM元素,示例:

<div>总价格:<span id="totalPrice">0</span> 美元</div>

核心逻辑说明

两个日期计算间隔晚数的核心逻辑:

  • 分别获取入住日期(date1)和离店日期(date2)的Date对象
  • 计算两个日期的毫秒差值,除以一天的毫秒数(10006060*24)后取整,得到实际入住晚数
  • 晚数乘以45美元/晚的单价,渲染到页面展示即可

完整修改后的代码

$(document).ready(function(){
  var array = <?php echo json_encode($seznamkoncni); ?>;

  // 公用总价计算函数,多处场景可复用
  function calculateTotalPrice() {
    var checkInDate = $('#date1').datepicker('getDate');
    var checkOutDate = $('#date2').datepicker('getDate');
    // 两个日期都选择完成后才执行计算
    if (checkInDate && checkOutDate) {
      // 计算天数差,自动处理夏令时、时区偏移导致的误差
      var timeDiff = checkOutDate.getTime() - checkInDate.getTime();
      var nightCount = Math.round(timeDiff / (1000 * 3600 * 24));
      var totalPrice = nightCount * 45;
      // 如需保留两位小数展示,可替换为 totalPrice.toFixed(2)
      $('#totalPrice').text(totalPrice);
    }
  }
  
  $('#date1').datepicker({
    minDate: 0,
    changeMonth: true, 
    changeYear: true,
    beforeShowDay: function(date){
      var string = jQuery.datepicker.formatDate('dd.mm.yy', date);
      return [ array.indexOf(string) == -1 ]  
    },
    onSelect: function(dateStr) {
      var newDate = $(this).datepicker('getDate');
      if (newDate) { 
        newDate.setDate(newDate.getDate() + 1);
      }
      $('#date2').datepicker('setDate', newDate).datepicker('option', 'minDate', newDate); 
      // 选择入住日期后如果已选离店日期,自动重新计算总价
      calculateTotalPrice();
    }
  });

  $('#date2').datepicker({
    minDate: 0,
    changeMonth: true, 
    changeYear: true,
    beforeShowDay: function(date){
      var string = jQuery.datepicker.formatDate('dd.mm.yy', date);
      return [ array.indexOf(string) == -1 ]
    },
    // 新增离店日期选中回调,触发总价计算
    onSelect: function() {
      calculateTotalPrice();
    }
  });
});

注意事项

  • 原代码中重复定义的DisableDates函数和未声明的dates变量没有实际生效,建议删除避免后续出现报错
  • 如果需要限制最短入住天数,可以在计算完nightCount后加判断逻辑,小于指定天数时给出提示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 20:15:05