JavaScript Tutorial: How to Set Default Start Date as 30 Days Prior & End Date as Current Date for Calendar Inputs
Calendar inputs (<input type="date">) are widely used in web applications for collecting date ranges—think analytics dashboards, booking systems, or report generators. A common user experience (UX) best practice is to pre-populate these inputs with sensible defaults, such as a start date 30 days prior and an end date as the current date. This saves users time and reduces errors by eliminating manual date selection.
In this tutorial, we’ll walk through how to achieve this using JavaScript. We’ll cover date calculation, formatting, and setting input values, with practical examples and solutions to common pitfalls. By the end, you’ll be able to implement dynamic default dates for calendar inputs in your projects.
Table of Contents#
- Prerequisites
- Understanding the Requirement
- Step 1: Create the HTML Structure
- Step 2: JavaScript Date Calculation & Formatting
- Step 3: Set Default Values for Calendar Inputs
- Complete Example Code
- Testing the Implementation
- Customization Options
- Common Issues & Solutions
- Conclusion
- References
Prerequisites#
Before starting, ensure you have:
- Basic knowledge of HTML (to create input elements).
- Familiarity with JavaScript fundamentals (selecting DOM elements, working with
Dateobjects). - A code editor (e.g., VS Code) and a web browser (to test the code).
Understanding the Requirement#
Our goal is to set two calendar inputs:
- Start Date: Defaults to 30 days before the current date.
- End Date: Defaults to the current date.
For example, if today is 2024-05-20, the start date should be 2024-04-20 (30 days prior), and the end date should be 2024-05-20.
Step 1: Create the HTML Structure#
First, we’ll add two <input type="date"> elements to our HTML. These will serve as the start and end date pickers. We’ll assign unique IDs to target them with JavaScript later.
<!-- Date Range Inputs -->
<div class="date-container">
<label for="start-date">Start Date:</label>
<input type="date" id="start-date" name="start-date">
<label for="end-date">End Date:</label>
<input type="date" id="end-date" name="end-date">
</div>Add basic CSS (optional) to style the inputs:
.date-container {
display: flex;
gap: 20px;
margin: 20px;
padding: 20px;
border: 1px solid #ddd;
border-radius: 8px;
}
label {
font-weight: bold;
margin-right: 8px;
}
input[type="date"] {
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
}Step 2: JavaScript Date Calculation & Formatting#
JavaScript’s Date object will help us calculate and manipulate dates. We’ll need to:
- Get the current date (for the end date).
- Subtract 30 days from the current date (for the start date).
- Format both dates as
YYYY-MM-DD(the required format for<input type="date">).
4.1 Calculate the Current Date (End Date)#
The Date object in JavaScript represents a single moment in time. To get the current date, create a new Date instance without arguments:
const today = new Date(); // Current date and time (local time zone)4.2 Calculate the Start Date (30 Days Prior)#
To get the date 30 days prior, we’ll modify the today object using setDate(), which sets the day of the month. Subtracting 30 from the current day of the month automatically handles month/year rollovers (e.g., March 1 - 30 days = January 30).
const thirtyDaysPrior = new Date(today); // Copy the current date
thirtyDaysPrior.setDate(today.getDate() - 30); // Subtract 30 days4.3 Format Dates as YYYY-MM-DD#
The <input type="date"> element expects dates in YYYY-MM-DD format (e.g., 2024-05-20). However, JavaScript’s Date methods return:
getFullYear(): 4-digit year (e.g., 2024).getMonth(): 0-based month (0 = January, 11 = December) → we’ll add 1 to get 1-12.getDate(): Day of the month (1-31) → may need leading zeros (e.g., 5 → "05").
We’ll create a helper function to format dates correctly:
function formatDate(date) {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0'); // Pad with leading zero
const day = String(date.getDate()).padStart(2, '0'); // Pad with leading zero
return `${year}-${month}-${day}`;
}Why padStart(2, '0')?
Months/days < 10 (e.g., March = 3, 5th of the month = 5) would otherwise become 2024-3-5, which is invalid. padStart(2, '0') ensures they become 03 and 05, resulting in 2024-03-05.
Step 3: Set Default Values for Calendar Inputs#
Now, we’ll select the calendar inputs by their IDs and set their value property to the formatted dates.
// Select the input elements
const startDateInput = document.getElementById('start-date');
const endDateInput = document.getElementById('end-date');
// Set default values
startDateInput.value = formatDate(thirtyDaysPrior);
endDateInput.value = formatDate(today);Complete Example Code#
Here’s the full HTML file with HTML, CSS, and JavaScript combined:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Default Date Range Example</title>
<style>
.date-container {
display: flex;
gap: 20px;
margin: 20px;
padding: 20px;
border: 1px solid #ddd;
border-radius: 8px;
}
label {
font-weight: bold;
margin-right: 8px;
}
input[type="date"] {
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
}
</style>
</head>
<body>
<div class="date-container">
<label for="start-date">Start Date:</label>
<input type="date" id="start-date" name="start-date">
<label for="end-date">End Date:</label>
<input type="date" id="end-date" name="end-date">
</div>
<script>
// Helper function to format date as YYYY-MM-DD
function formatDate(date) {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
// Calculate dates
const today = new Date();
const thirtyDaysPrior = new Date(today);
thirtyDaysPrior.setDate(today.getDate() - 30);
// Set input values
const startDateInput = document.getElementById('start-date');
const endDateInput = document.getElementById('end-date');
startDateInput.value = formatDate(thirtyDaysPrior);
endDateInput.value = formatDate(today);
</script>
</body>
</html>Testing the Implementation#
- Save the code above as
index.html. - Open it in a web browser (e.g., Chrome, Firefox).
- You’ll see two calendar inputs:
- The start date will default to 30 days before today.
- The end date will default to today.
Customization Options#
8.1 Change the Number of Days (e.g., 7 Days Prior)#
To set the start date to 7 days prior (1 week), modify the setDate call:
// 7 days prior instead of 30
thirtyDaysPrior.setDate(today.getDate() - 7); 8.2 Set End Date to a Custom Value (e.g., Yesterday)#
To set the end date to yesterday instead of today:
const yesterday = new Date(today);
yesterday.setDate(today.getDate() - 1); // Subtract 1 day
endDateInput.value = formatDate(yesterday);Common Issues & Solutions#
9.1 Time Zone Discrepancies#
Problem: The Date object uses the user’s local time zone. If the user is in a time zone behind UTC (e.g., UTC-5), the "current date" might differ from UTC. For example, 1 AM UTC-5 is still the previous day in UTC.
Solution: For client-side defaults, local time is acceptable. If your server expects UTC dates, adjust the date to UTC before formatting:
// Convert to UTC before formatting (for server-side UTC)
function formatUTCDate(date) {
const year = date.getUTCFullYear();
const month = String(date.getUTCMonth() + 1).padStart(2, '0');
const day = String(date.getUTCDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}9.2 Missing Leading Zeros in Dates#
Problem: If months/days are not padded with leading zeros (e.g., 2024-3-5 instead of 2024-03-05), the input will not recognize the date.
Solution: Always use padStart(2, '0') for months and days, as shown in the formatDate function.
9.3 Inputs Not Updating (Element Selection Issues)#
Problem: The script runs before the input elements are loaded, so document.getElementById returns null.
Solution:
- Place the
<script>tag after the input elements in the HTML (as in the example). - Or wrap the code in a
DOMContentLoadedevent listener to ensure the DOM is fully loaded:
document.addEventListener('DOMContentLoaded', () => {
// All code here (formatDate, date calculations, setting values)
});Conclusion#
Setting default dates for calendar inputs improves UX by reducing manual effort. With JavaScript’s Date object and a simple formatting helper, you can dynamically set start (30 days prior) and end (current date) dates. This tutorial covered calculation, formatting, customization, and troubleshooting to ensure a robust implementation.