如何通过jQuery在datetime-local上设置datetime

Vla*_*den 17 html javascript jquery html5

我的表单上有datetime-local html控件,我需要通过JS或jQuery动态设置日期和时间.我该怎么做?

<input type="datetime-local" id="publishDate" required/>
Run Code Online (Sandbox Code Playgroud)

我试过了

$("#publishDate").val("2013-3-18 13:00");
$("#publishDate").val("2013-3-18T13:00");
$("#publishDate").val(new Date().toLocalString());
Run Code Online (Sandbox Code Playgroud)

但没有任何效果.

提前致谢.

Cla*_*edi 19

这样就可以了

$("#publishDate").val("2013-03-18T13:00");
Run Code Online (Sandbox Code Playgroud)

您需要使用月份的2位数来使您的样本工作.


Var*_*aaj 12

如果要设置当前日期,则可以尝试以下操作:

__Method 1:__

$(document).ready(function(){
    $('input[type=datetime-local]').val(new Date().toJSON().slice(0,19));
});

__Method 2:__

function zeroPadded(val) {
  if (val >= 10)
    return val;
  else
    return '0' + val;
}

$(document).ready(function(){
  d = new Date();
  $('input[type=datetime-local]').val(d.getFullYear()+"-"+zeroPadded(d.getMonth() + 1)+"-"+zeroPadded(d.getDate())+"T"+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds());
});
Run Code Online (Sandbox Code Playgroud)

注意:您可以将其替换$("输入[类型=日期时间本地]")IdNameClass将datetime-局部领域.

编辑:d.getMonth()返回0-11之间的值,因此要输入正确的月份1需要添加到结果中.

  • **注意**`new Date().toJSON().slice(0,19)`和`new Date().toISOString().slice(0,19)`都返回UTC时间,而不是__local time__. (4认同)
  • 我稍微修改了脚本,您需要在小时、分钟和秒上使用“zeroPadded”函数,否则您会收到错误。`$('input[type=datetime-local]').val(d.getFullYear()+"-"+zeroPadded(d.getMonth() + 1)+"-"+zeroPlated(d.getDate()) +“T”+zeroPadded(d.getHours())+“:”+zeroPlated(d.getMinutes())+“:”+zeroPadded(d.getSeconds()));` (2认同)

kla*_*xxx 10

关于什么?

var now=new Date();
console.log(new Date(now.getTime()-now.getTimezoneOffset()*60000).toISOString().substring(0,19));
Run Code Online (Sandbox Code Playgroud)


小智 6

这是使用 momentjs 格式化日期的解决方案。
这将获取当前日期和时间

moment().format('YYYY-MM-DDThh:mm:ss.SSS')
Run Code Online (Sandbox Code Playgroud)


rb-*_*rb- 5

我写了一个jQuery方法来设置当前的UTC时间.它对初始化datetimedatetime-local输入字段很有用.

以下是如何使用它来初始化字段.

$('input[type="datetime"]').setNow();
Run Code Online (Sandbox Code Playgroud)

或者传递一个参数,true只设置没有值的字段.

$('input[type="datetime"]').setNow(true);
Run Code Online (Sandbox Code Playgroud)