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

如何用JavaScript将input type="date"转为当月最后一天(YYYY-MM-DD格式)

解决方案:将日期输入框自动设置为当月最后一天

要实现用户选择任意日期后,输入框自动显示该日期所属月份的最后一天(格式为YYYY-MM-DD),可以通过以下步骤完成:

实现思路

  • 监听日期输入框的change事件,用户选择日期后立即触发处理
  • 利用JavaScript Date对象的特性:当构造日期时将日期参数设为0,会返回上一个月的最后一天。因此,我们只需要构造用户选中日期的「下一个月的第0天」,就能得到当前月的最后一天
  • 将计算出的日期格式化为YYYY-MM-DD标准格式,再赋值回输入框

完整代码

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Test</title>
  </head>
  <style media="screen">
  .form-question {
    display: flex;
    flex-direction: column;
    justify-content: center;
    margin: 0 0 3rem;
    min-height: 3rem;
  }
  .form-question__title {
    color: #342357;
    font-size: 1.5rem;
    padding: 1rem;
  }
  .input-container {
    border-bottom: solid 2px #333333;
  }
  .input-container input {
    border: none;
    box-sizing: border-box;
    outline: 0;
    padding: .75rem;
    width: 100%;
  }
  </style>
  <body>
    <div class="form-question">
      <div class="form-question__title">
        <span>Effective Date</span>
      </div>
      <div class="input-container">
        <input id="effective-date" type="date" name="effective-date" minlength="1" maxlength="64" placeholder=" " autocomplete="nope" required="required">
        <span class="bar"></span>
      </div>
    </div>

    <script>
      // 获取日期输入框元素
      const dateInput = document.getElementById('effective-date');

      // 计算并返回指定日期所属月份最后一天的YYYY-MM-DD格式字符串
      function getLastDayOfMonth(dateStr) {
        const selectedDate = new Date(dateStr);
        // 构造下一个月的第0天,即当前月的最后一天
        const lastDayOfMonth = new Date(selectedDate.getFullYear(), selectedDate.getMonth() + 1, 0);
        
        // 格式化为YYYY-MM-DD,确保月份和日期是两位数字
        const year = lastDayOfMonth.getFullYear();
        const month = String(lastDayOfMonth.getMonth() + 1).padStart(2, '0');
        const day = String(lastDayOfMonth.getDate()).padStart(2, '0');
        
        return `${year}-${month}-${day}`;
      }

      // 监听日期选择变化事件
      dateInput.addEventListener('change', function() {
        if (this.value) {
          const lastDayStr = getLastDayOfMonth(this.value);
          this.value = lastDayStr;
        }
      });
    </script>
  </body>
</html>

关键细节说明

  1. 核心日期计算逻辑:new Date(selectedDate.getFullYear(), selectedDate.getMonth() + 1, 0)

    • 因为JavaScript的Date对象中月份是0索引(0代表1月,11代表12月),所以selectedDate.getMonth() + 1指向选中日期的下一个月
    • 将日期参数设为0,会自动回退到上一个月的最后一天,也就是我们需要的当前月最后一天
  2. 格式补零处理:padStart(2, '0')

    • 确保月份和日期始终以两位数字显示,避免出现2023-6-3这种不符合YYYY-MM-DD格式的结果
  3. 事件监听:绑定change事件可以覆盖用户通过选择器选择日期、手动输入日期(部分浏览器支持)等所有修改输入框值的场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 17:22:42