简体   繁体   English

如何在html的输入文本框中打印日期

[英]how to print date in input text box in html

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>

You have to 你必须

  • correctly create the Date object (you're missing new ) 正确创建Date对象(你错过了new
  • format it according to rfc3339 (ex: 2012/12/30 ) 根据格式化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;

Demonstration 示范

Note that some browsers accept other formats, but Chrome doesn't, as it complies to the norm . 请注意,某些浏览器接受其他格式,但Chrome不接受其他格式,因为它符合规范

The value attribute of the input box is a string, but your function is trying to assign a Date object. 输入框的value属性是一个字符串,但您的函数正在尝试分配Date对象。 You need to convert it to a string first. 您需要先将其转换为字符串。 Here's some code that will do it: 这里有一些代码可以做到:

<!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>

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 - day while the new Date() in JavaScript returns date like eg: Sun Dec 30 2012 10:09:05 GMT+0230 HTML5中的日期控件接受格式为Year - month - day,而JavaScript中的new Date()返回日期,例如: Sun Dec 30 2012 10:09:05 GMT + 0230

See demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM