javascript 如何在html的输入文本框中打印日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14092851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to print date in input text box in html
提问by Ankit Mishra
here is my code,i want to print date in text box after enter date text using onload event.
这是我的代码,我想在使用 onload 事件输入日期文本后在文本框中打印日期。
<!DOCTYPE html>
<html>
<head>
<script>
function displayDate() {
document.getElementById("fname").value = Date();
}
</script>
</head>
<body onload="displayDate()">
Enter date: <input type="date" id="fname" readonly />
</body>
</html>
回答by Denys Séguret
You have to
你必须
- correctly create the
Date
object (you're missingnew
) - format it according to rfc3339(ex:
2012/12/30
)
- 正确创建
Date
对象(你错过了new
) - 根据格式化rfc3339(例如:
2012/12/30
)
Change
改变
document.getElementById("fname").value = Date();
to
到
var now = new Date();
var formatedDate = now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + now.getDate();?
document.getElementById("fname").value = formatedDate;
Note that some browsers accept other formats, but Chrome doesn't, as it complies to the norm.
请注意,某些浏览器接受其他格式,但 Chrome 不接受,因为它符合规范。
回答by Michael Oliver
The value attribute of the input box is a string, but your function is trying to assign a Date object. You need to convert it to a string first. Here's some code that will do it:
输入框的 value 属性是一个字符串,但您的函数正在尝试分配一个 Date 对象。您需要先将其转换为字符串。这是一些可以做到的代码:
<!DOCTYPE html>
<html>
<head>
<script>
function displayDate() {
var today=new Date();
var date=today.toISOString().slice(0, -14);
// Strip last 14 characters, ISO format is like
// 2012-12-30T17:41:49.027Z but we want
// 2012-12-30
document.getElementById("fname").value=date;
}
</script>
</head>
<body onload="displayDate()">
Enter date: <input type="date" id="fname" readonly>
</body>
</html>
回答by Anujith
Try this:
试试这个:
function displayDate() {
var now = new Date();
var day = ("0" + now.getDate()).slice(-2);
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var today = now.getFullYear() + "-" + (month) + "-" + (day);
document.getElementById("fname").value = today;
}?
Date control in HTML5 accepts in the format of Year - month - daywhile the new Date()
in JavaScript returns date like eg: Sun Dec 30 2012 10:09:05 GMT+0230
HTML5 中的日期控件接受年 - 月 - 日的格式,而new Date()
JavaScript 中的返回日期如:Sun Dec 30 2012 10:09:05 GMT+0230
See demo
看演示