先看显示效果:
html代码:<input type="datetime-local" id="currentDate">
jQuery代码:
$(function(){
var today = new Date();//返回当前日期和时间
var yyyy = today.getFullYear();//获取当前年份
var MM = today.getMonth() + 1;//因为getMonth()方法获取的是索引值,获取的月份为0-11,所以要+1
var dd = today.getDate();//从 Date 对象返回一个月中的某一天 (1 ~ 31)
var hh = today.getHours();//返回 Date 对象的小时 (0 ~ 23)
var mm = today.getMinutes();//返回 Date 对象的分钟 (0 ~ 59)
MM = checkTime(MM);//调用下面的checkTime函数,设置小于10的时间数字格式,例如5秒显示成05秒
dd = checkTime(dd);
hh = checkTime(hh);
mm = checkTime(mm);
var time = yyyy + "-" + MM + "-" + dd + "T" + hh + ":" + mm;
var dateControl = document.querySelector("#availableFrom");
dateControl.value = time;
function checkTime(i) {
if (i < 10) {
i = "0" + i;//这里如果是一位数则在前面添加一位0
}
return i;`
});
需注意:var time = yyyy + “-” + MM + “-” + dd + “T” + hh + “:” + mm;中的"T"是必须要加上的,此处T表示time元素的开始;
字符 | 含义 |
---|---|
YYYY | is the decimal digits of the year 0000 to 9999 in the Gregorian calendar. |
- | “-” (hyphen) appears literally twice in the string. |
MM | is the month of the year from 01 (January) to 12 (December). |
DD | is the day of the month from 01 to 31. |
T | “T” appears literally in the string, to indicate the beginning of the time element. |
HH | is the number of complete hours that have passed since midnight as two decimal digits from 00 to 24. |
: | “:” (colon) appears literally twice in the string. |
mm | is the number of complete minutes since the start of the hour as two decimal digits from 00 to 59. |
ss | is the number of complete seconds since the start of the minute as two decimal digits from 00 to 59. |
. | “.” (dot) appears literally in the string. |
sss | is the number of complete milliseconds since the start of the second as three decimal digits. |
Z | is the time zone offset specified as “Z” (for UTC) or either “+” or “-” followed by a time expression HH:mm |