MattsBits
MattsBits

MattsBits

JavaScript Function to Set Current Date and Time  

by Matt Hawkins, 08/02/2012
Categories : JavaScript

This JavaScript function shows how you can populate two text boxes with the current date and time when clicking an HTML button.

To demonstrate the function cut and paste the following HTML and JavaScript into a new text file and name it "test.html".


<html>
<title>MattsBits JavaScript Set Time Date</title>
<body>

<script>
function SetDateNow() {

  var MyDate;
  var MyTime;

  // Define and set current date and time vars
  var currentDate = new Date();
  var day = currentDate.getDate();
  var month = currentDate.getMonth()+1;
  var year = currentDate.getFullYear();
  var hours = currentDate.getHours();
  var minutes = currentDate.getMinutes();

  // Make sure numbers are two digits
  // pad with zeroes if less than 10.
  day   = (day<10) ? '0'+day : ''+day;
  month = (month<10) ? '0'+month : ''+month;
  hours   = (hours<10) ? '0'+hours : ''+hours;
  minutes = (minutes<10) ? '0'+minutes : ''+minutes;

  // Construct date and time strings in required format
  MyDate = day + "/" + month + "/" + year;
  MyTime = hours + ":" + minutes;

  // Update text boxes
  document.getElementById("idate").value = MyDate;
  document.getElementById("itime").value = MyTime;

}
</script>

<fieldset><legend>Date &amp; Time</legend>
<input type="text" id="idate" size="10" maxlength="10" value="01/01/2012" />
<input type="text" id="itime" size="5"  maxlength="5"  value="12:00" />
<input type="button" onclick="SetDateNow();" value="Set Now!"/>
</fieldset>

<p>Click the button to trigger the SetDateNow() function.
This will populate the date and time text boxes with the current date and time.</p>

</body>
</html>


Load the file into your browser and note the date and time. These default values are defined in the HTML. Click the button and this will trigger the SetDateNow() function. The text boxes will be updated with the current date and time.

Author : Matt Hawkins  Last Edit By : Matt Hawkins
PHP Powered  MySQL Powered  Valid XHTML 1.0  Valid CSS  Firefox - Take Back The Web  EUKHost - Recommended Webhosting Solutions

MattHawkins CMS v3.0 - Copyright 2009-2017