When creating forms that require users to select a date and time, it’s often helpful to prefill the input with the current date and time. This small convenience can save users a bit of time and ensure that the most relevant time is readily available. In this article, we’ll walk through the HTML and JavaScript needed to automatically set the current date and time in a datetime-local input field.
HTML Structure
First, let's look at the basic structure of our HTML document. This includes a form with a datetime-local input and a submit button.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Date and Time Input</title>
</head>
<body>
<form>
<label for="datetime">Select date and time:</label>
<input type="datetime-local" id="datetime" name="datetime">
<input type="submit" value="Submit">
</form>
</body>
</html>
In this form, the <input>
element with the type datetime-local
allows users to select both a date and a time.
JavaScript to Set the Current Date and Time
Next, we need to add some JavaScript to automatically set the current date and time when the page loads. We'll achieve this by adding a script that runs as soon as the DOM content is fully loaded.
<script>
document.addEventListener('DOMContentLoaded', (event) => {
// Function to add a leading zero to single digit numbers
function addLeadingZero(number) {
return (number < 10 ? '0' : '') + number;
}
// Get the current date and time
const now = new Date();
const year = now.getFullYear();
const month = addLeadingZero(now.getMonth() + 1); // Months are zero-indexed
const day = addLeadingZero(now.getDate());
const hours = addLeadingZero(now.getHours());
const minutes = addLeadingZero(now.getMinutes());
// Format the datetime string in the format required by datetime-local input
const currentDatetime = `${year}-${month}-${day}T${hours}:${minutes}`;
// Set the value of the datetime-local input to the current date and time
document.getElementById('datetime').value = currentDatetime;
});
</script>
Explanation of the JavaScript Code
- Event Listener: We use
document.addEventListener('DOMContentLoaded', ...)
to ensure our code runs only after the entire HTML document has been loaded and parsed. - Helper Function: The function
addLeadingZero(number)
ensures that single-digit numbers (e.g., 5) are prefixed with a zero (e.g., 05), which is necessary for the correct datetime format. - Get Current Date and Time: We create a new
Date
object to get the current date and time. - Format Date and Time: We extract the year, month, day, hours, and minutes from the
Date
object. Note that months are zero-indexed in JavaScript, so we add 1 to the month. - Set Input Value: Finally, we format the extracted values into a string that matches the required format for
datetime-local
inputs (YYYY-MM-DDTHH:MM
) and set this string as the value of our datetime input.
Related Articles:
- Automatically Setting the Current Date and Time in an HTML Form
- How to Create a Spinner with Loading Data Percentage in DataTables
- Convert Numbers to Khmer Number System Words (HTML+JAVASCRIPT)
- Converting Numbers to Words in JavaScript
- Create Login Form Using HTML, CSS, JavaScript
- JavaScript – Create Notes App