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