0

how can i have automatic current date in the text box when i load the page with the format yyyy-mm-dd

       <tr><td>*Date:</td></tr>
 <tr><td><div id="ma"><input type="text" name="dte" id="text1">  </div> 
  <script type="text/javascript">    
   document.getElementById("text1").value = Date().toString();    
 </script>    
  </td></tr>
Ken White
  • 123,280
  • 14
  • 225
  • 444

5 Answers5

2

I don't have enough reputation so that I cannot add the comments to Mike.

Just like Mike's solution, but there are some small mistakes:

  1. getDay() return the weekday a number (0-6), so you should use getDate()
  2. getMonth() return 0-11, so you should +1.

    var d = new Date();
    
    var day = d.getDate();
    var month = d.getMonth() + 1;
    var year = d.getFullYear();
    
    if (Math.floor(day / 10) === 0) {
        day = "0" + day;
    }
    if (Math.floor(month / 10) === 0) {
        month = "0" + month;
    }
    
    document.getElementById("text1").value = year + "-" + month + "-" + day;
    
Leo SHEN
  • 86
  • 1
  • 4
1

A simple solution would be just doing something like this:

var d = new Date();

var day = d.getDate();
var month = d.getMonth() + 1;
var year = d.getFullYear();

if (Math.floor(day / 10) === 0) {
    day = "0" + day;
}
if (Math.floor(month / 10) === 0) {
    month = "0" + month;
}

document.getElementById("text1").value = year + "-" + month + "-" + day;

EDIT: Fixed errors caught by Guozi.

Mike Z
  • 77
  • 8
1

If you are doing a lot of formatting, you may want to consider moment.js. With it, you could easily set the value using:

moment().format('YYYY-MM-DD');

If you are only formatting that one date, then it may not be worth the overhead, but as a library, it permits you to keep your site-specific JS clean.

vol7ron
  • 40,809
  • 21
  • 119
  • 172
1

What you want to do is to write a date in ISO 8601 format in JavaScript. There are several ways to do it. The following is a simple plain JavaScript way and works across browsers:

function toISO8601(date) {
  var d  = date.getDate();
  if(d < 10) d = '0' + d;
  var m = date.getMonth() + 1;
  if(m < 10) m = '0' + m;
  return date.getFullYear() + '-' + m + '-' +  d;
}
document.getElementById("text1").value = toISO8601(Date()); 
Jukka K. Korpela
  • 195,524
  • 37
  • 270
  • 390
0

When using php this is also a good option:

<input type="text" name="dte" id="text1" value="<?= date("Y-m-d") ?>">
Vennik
  • 565
  • 3
  • 11