HTML5 Input datetime-本地默认值今天和当前时间

新手上路,请多包涵

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

之前谢谢

原文由 Christian Sakai 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.4k
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>

查询:

 //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();

});

原文由 Nicolas Henrard 发布,翻译遵循 CC BY-SA 3.0 许可协议

你可以让它更短:

 <input type="datetime-local" id="cal">

 window.addEventListener('load', () => {
  var now = new Date();
  now.setMinutes(now.getMinutes() - now.getTimezoneOffset());

  /* remove second/millisecond if needed - credit ref. https://stackoverflow.com/questions/24468518/html5-input-datetime-local-default-value-of-today-and-current-time#comment112871765_60884408 */
  now.setMilliseconds(null)
  now.setSeconds(null)

  document.getElementById('cal').value = now.toISOString().slice(0, -1);
});

原文由 takatama 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题