【问题标题】:HTML5 Input datetime-local default value of today and current timeHTML5 输入 datetime-local 今天和当前时间的默认值
【发布时间】:2014-06-28 15:55:03
【问题描述】:

无论如何我可以将 HTML5 input type='datetime-local' 的默认值设置为今天的日期和当前时间。

感谢之前

【问题讨论】:

    标签: html


    【解决方案1】:

    你可以让它更短:

    <input type="datetime-local" id="cal">
    
    window.addEventListener('load', () => {
      const now = new Date();
      now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
      document.getElementById('cal').value = now.toISOString().slice(0, -1);
    });
    

    【讨论】:

    • 在 Firefox 中,我必须缩短秒数 (-8) 才能使表单验证。
    • 最佳响应在这里,如果你想删除毫秒,只需添加now.setMilliseconds(null)
    【解决方案2】:

    这是可能的。通过使用 JQuery 函数,您可以获得真正完整的解决方案。

    这是一个例子。

    JSFiddle http://jsfiddle.net/v8MNx/1/

    HTML

    <form action="demo.html" id="myForm">
        <p>
            <label>Date:</label>
            <input type="datetime" name="anniversaire" id="anniversaire"/>
        </p>
        <input type="submit" value="Submit"/>
    </form>
    

    JQuery:

    //Function found here: https://gist.github.com/ryanburnette/8803238
    $.fn.setNow = function (onlyBlank) {
      var now = new Date($.now())
        , year
        , month
        , date
        , hours
        , minutes
        , seconds
        , formattedDateTime
        ;
    
      year = now.getFullYear();
      month = now.getMonth().toString().length === 1 ? '0' + (now.getMonth() + 1).toString() : now.getMonth() + 1;
      date = now.getDate().toString().length === 1 ? '0' + (now.getDate()).toString() : now.getDate();
      hours = now.getHours().toString().length === 1 ? '0' + now.getHours().toString() : now.getHours();
      minutes = now.getMinutes().toString().length === 1 ? '0' + now.getMinutes().toString() : now.getMinutes();
      seconds = now.getSeconds().toString().length === 1 ? '0' + now.getSeconds().toString() : now.getSeconds();
    
      formattedDateTime = year + '-' + month + '-' + date + 'T' + hours + ':' + minutes + ':' + seconds;
    
      if ( onlyBlank === true && $(this).val() ) {
        return this;
      }
    
      $(this).val(formattedDateTime);
    
      return this;
    }
    
    $(function () {
        // Handler for .ready() called.
        $('input[type="datetime"]').setNow();
    
    });
    

    【讨论】:

    【解决方案3】:

    接受的答案对我来说似乎很复杂......这里是一个不需要 jQuery 的较短解决方案

    JSFiddle: https://jsfiddle.net/rzaceg8v/

    window.addEventListener("load", function() {
        var now = new Date();
        var utcString = now.toISOString().substring(0,19);
        var year = now.getFullYear();
        var month = now.getMonth() + 1;
        var day = now.getDate();
        var hour = now.getHours();
        var minute = now.getMinutes();
        var second = now.getSeconds();
        var localDatetime = year + "-" +
                          (month < 10 ? "0" + month.toString() : month) + "-" +
                          (day < 10 ? "0" + day.toString() : day) + "T" +
                          (hour < 10 ? "0" + hour.toString() : hour) + ":" +
                          (minute < 10 ? "0" + minute.toString() : minute) +
                          utcString.substring(16,19);
        var datetimeField = document.getElementById("myDatetimeField");
        datetimeField.value = localDatetime;
    });
    &lt;input type="datetime-local" id="myDatetimeField"/&gt;

    【讨论】:

    • 默认值设置好了,但是为什么从选择器中选择另一个日期/时间时它没有改变?
    • 这是个好问题。它曾经可以工作,现在仍然可以在基于 Chromium 的 Edge 中工作。我认为这可能是新 Chrome 版本中的错误。
    【解决方案4】:

    上述方法有效,但对我来说太冗长了。 这是我的版本:

    window.addEventListener("load", function() {
        var now = new Date();
        var offset = now.getTimezoneOffset() * 60000;
        var adjustedDate = new Date(now.getTime() - offset);
        var formattedDate = adjustedDate.toISOString().substring(0,16); // For minute precision
        var datetimeField = document.getElementById("myDatetimeField");
        datetimeField.value = formattedDate;
    });
    
    

    【讨论】:

      【解决方案5】:

      这很完美!

      请注意,我在 10 月这个唯一会中断的月份尝试了这个。它会给我一个“010”,而不是 10。

      month = (now.getMonth() +1 ).toString().length === 1 ? '0' + (now.getMonth() + 1).toString() : now.getMonth() + 1;

      【讨论】:

        【解决方案6】:

        大行适合我,如果不适合你,你可以在表达式中引入空格和换行符。

        function setDatetimeInput(element, t = new Date()){
            function p(number){return number.toString().padStart(2, '0');}//number to 2 digit, 0 padded string
            element.value = `${t.getFullYear()}-${p(t.getMonth()+1)}-${p(t.getDate())}T${p(t.getHours())}:${p(t.getMinutes())}`;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2023-04-09
          • 2014-10-09
          • 1970-01-01
          • 2015-03-02
          • 2021-10-25
          • 1970-01-01
          • 2020-04-03
          相关资源
          最近更新 更多