给定一个输入元素:

<input type="date" />

有没有办法将日期字段的默认值设置为今天的日期?


当前回答

这里有一个简单的方法来做到这一点与javascript。

    var date = new Date();
    var datestring = ('0000' + date.getFullYear()).slice(-4) + '-' + ('00' + (date.getMonth() + 1)).slice(-2) + '-' + ('00' + date.getDate()).slice(-2) + 'T'+  ('00' +  date.getHours()).slice(-2) + ':'+ ('00' + date.getMinutes()).slice(-2) +'Z';
    document.getElementById('MyDateTimeInputElement').value = datestring;

其他回答

这是服务器端真正需要做的事情,因为每个用户的本地时间格式不同,更不用说每个浏览器的行为不同了。

Html日期输入的值应该是这样的格式:yyyy-mm-dd,否则它不会显示一个值。

Asp classic或vbscript:

current_year = DatePart("yyyy",date) 
current_month = DatePart("m",date) 
current_day = DatePart("d",date) 

IF current_month < 10 THEN
current_month = "0"&current_month
END IF
IF current_day < 10 THEN
current_day = "0"&current_day
END IF

get_date = current_year&"-"&current_month&"-"&current_day
Response.Write get_date

今日内容:2019-02-08

然后在你的html中: <input type="date" value="<% =get_date %>"

PHP

就用这个吧: <input type="date" value="<? "=日期(“Y-m-d”);”? > >

现在,我们不应该再使用moment.js,而是使用day.js来处理这个问题,而且没有任何副作用。js很棒,但它并没有向前推进,它相对较大,但非常有用。js具有足够好的特性,足以成为未来几年使用的新候选。

let now = dayjs(); /* same as now = dayjs(new Date()); */

最简单的解决方案似乎忽略了将使用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
$(document).ready(function(){
  var date = new Date();

  var day = ("0" + date.getDate()).slice(-2); var month = ("0" + (date.getMonth() + 1)).slice(-2);

  var today = date.getFullYear()+"-"+(month)+"-"+(day) ;
});

$('#dateid').val(today);

使用moment.js在2行中解决这个问题, html5日期输入类型只接受“YYYY-MM-DD”这种格式。我用这种方法解决问题。

var today = moment().format('YYYY-MM-DD');
 $('#datePicker').val(today);

这是解决这个问题最简单的方法。