给定一个输入元素:
<input type="date" />
有没有办法将日期字段的默认值设置为今天的日期?
给定一个输入元素:
<input type="date" />
有没有办法将日期字段的默认值设置为今天的日期?
当前回答
现在,我们不应该再使用moment.js,而是使用day.js来处理这个问题,而且没有任何副作用。js很棒,但它并没有向前推进,它相对较大,但非常有用。js具有足够好的特性,足以成为未来几年使用的新候选。
let now = dayjs(); /* same as now = dayjs(new Date()); */
其他回答
如果你正在使用ruby,你可以使用这个来设置默认值为今天的日期和时间:
<input type="datetime-local" name="time" value="<%= Time.now.strftime('%Y-%m-%dT%H:%M') %>" />
对于NodeJS(带有SWIG模板的Express):
<input type="date" id="aDate" name="aDate" class="form-control" value="{{ Date.now() | date("Y-m-d") }}" />
如果你需要填写输入日期时间,你可以使用这个:
<input type="datetime-local" name="datetime"
value="<?php echo date('Y-m-d').'T'.date('H:i'); ?>" />
这依赖于PHP:
<input type="date" value="<?php echo date('Y-m-d'); ?>" />
最简单的解决方案似乎忽略了将使用UTC时间,包括高度赞成的解决方案。下面是一个精简的,ES6,非jquery版本的一对现有的答案:
const today = (function() {
const now = new Date();
const month = (now.getMonth() + 1).toString().padStart(2, '0');
const day = now.getDate().toString().padStart(2, '0');
return `${now.getFullYear()}-${month}-${day}`;
})();
console.log(today); // as of posting this answer: 2019-01-24