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

JavaScript日期加天数失效但减天数正常的技术问题

问题排查与解决方案

问题根源

问题出在天数参数的类型转换上:

  • DayRange输入框的取值是字符串类型(比如"10")
  • 在addDays函数中,newDate.getDate() + days会触发字符串拼接(因为+运算符遇到字符串时优先执行拼接逻辑),比如1 + "10"会变成"110",转成数字后传入setDate(),相当于给日期加了110天,导致结果严重偏离预期
  • 减法操作中,-运算符会自动将字符串转为数值,所以1 - "10"会正确计算为-9,因此减天数功能正常

修复方案

在获取myDays后,将其转为数值类型即可,推荐使用parseInt()(或Number())进行强制转换。

修改后的JavaScript代码

var dateFormat = "dd/mm/yy";

$(document).ready(function() {
  $("#AddBtn").click(function() {
    var myDate = $.datepicker.parseDate(
      dateFormat,
      document.getElementById("V1_Date").value
    );
    // 转为数值类型,第二个参数10表示十进制
    var myDays = parseInt(document.getElementById("DayRange").value, 10);
    myDate = addDays(myDate, myDays);
    var formattedDate = $.datepicker.formatDate(dateFormat, myDate);
    document.getElementById("ResultDate").value = formattedDate;
  });

  $("#SubBtn").click(function() {
    var myDate = $.datepicker.parseDate(
      dateFormat,
      document.getElementById("V1_Date").value
    );
    // 统一转为数值类型,保持代码一致性
    var myDays = parseInt(document.getElementById("DayRange").value, 10);
    myDate = subDays(myDate, myDays);
    var formattedDate = $.datepicker.formatDate(dateFormat, myDate);
    document.getElementById("ResultDate").value = formattedDate;
  });
});

var xDate = $("#V1_Date").datepicker({
  changeYear: true,
  changeMonth: true,
  dateFormat: dateFormat,
});

function addDays(date, days) {
  const newDate = new Date(date);
  newDate.setDate(newDate.getDate() + days);
  return newDate;
}

function subDays(date, days) {
  const newDate = new Date(date);
  newDate.setDate(newDate.getDate() - days);
  return newDate;
}

额外优化建议

给DayRange输入框加上type="number"属性,限制只能输入数字,避免非数值输入导致的异常:

<p>Days: <input type="number" value="10" id="DayRange" /></p>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 18:52:42