Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to Set an HTML Date Picker Max Date to Today?
In HTML, a date picker is a useful input control that enables users to select specific dates on websites or forms. By default, date pickers accept any date, but you can limit the selectable date range using the max attribute to restrict selection to today or earlier dates.
Syntax
<input type="date" max="YYYY-MM-DD">
What is a Date Picker?
A date picker is a user interface component that allows users to select dates through a calendar interface. It's commonly used in forms for applications like reservation systems, scheduling software, or collecting birthdates.
Setting Max Date to Today with JavaScript
To dynamically set the max attribute to today's date, you need JavaScript to generate the current date in YYYY-MM-DD format
HTML Structure
Create an input element with type="date"
<input type="date" id="datepicker">
Complete Example
Here's how to set the maximum selectable date to today using JavaScript
<!DOCTYPE html>
<html>
<head>
<title>Date Picker with Max Date</title>
</head>
<body>
<h3>Select a Date (Max: Today)</h3>
<input type="date" id="datepicker">
<script>
const today = new Date();
const year = today.getFullYear();
const month = String(today.getMonth() + 1).padStart(2, '0');
const day = String(today.getDate()).padStart(2, '0');
const formattedDate = `${year}-${month}-${day}`;
document.getElementById('datepicker').setAttribute('max', formattedDate);
</script>
</body>
</html>
A date picker input appears that only allows selection of dates up to and including today's date. Future dates are disabled and cannot be selected.
How the JavaScript Works
The JavaScript code performs these steps
- Creates a new Date object representing the current date
- Extracts the year, month, and day components
- Formats the month and day with leading zeros using
padStart() - Combines them into YYYY-MM-DD format required by the date input
- Sets the max attribute of the date picker
Use Cases
Restricting the maximum date to today is useful for
- Booking systems that only allow current or past date selections
- Birthday or event registration forms
- Data collection forms where future dates are not relevant
- Historical record entry systems
Conclusion
Setting an HTML date picker's max date to today prevents users from selecting future dates. Use JavaScript to dynamically generate today's date in YYYY-MM-DD format and apply it to the input's max attribute for real-time date restriction.
