JavaScript Date - Add, Subtract and Finding the Difference

How to Create a Date Calculator Using JavaScript 


How to Create a Date Calculator Using JavaScript


In this Javascript tutorial, we will see how to create a dates calculator, where you can enter two dates, add or subtract a certain number of days from one of the dates, and calculate the difference in days between two dates.




Project Source Code:



<!DOCTYPE html>
<html>
<head>
<title>Date Difference Calculator</title>
<style>
body{ font-family: Arial, Helvetica, sans-serif; background-color: #555; }

form{ display: flex; flex-direction: column; max-width: 400px; margin: 0 auto;
padding: 20px; border-radius: 5px; background-color: #fff;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
}
label{ margin-bottom: 5px; font-weight: bold; }

input[type="text"],
input[type="number"],
select{ padding: 10px; margin-bottom: 10px; border-radius: 5px;
border: 1px solid #ccc; background-color: #f2f2f2;
}

input[type="button"]{ padding: 10px 20px; border: none; border-radius: 5px;
background-color: #008cba; color: #fff; cursor: pointer;
margin-bottom: 5px; transition: all 0.3s ease;
}
input[type="button"]:hover{ background-color: #006f8b; }

#result{ max-width: 400px; margin: 20px auto; padding: 20px; border-radius: 5px;
background-color: #fff; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
}

</style>
</head>
<body>

<form id="date-form">
<label for="start-date">Start Date:</label>
<input type="text" id="start-date" placeholder="yyyy-mm-dd">
<br>
<label for="end-date">End Date:</label>
<input type="text" id="end-date" placeholder="yyyy-mm-dd">
<br>
<label for="days">Days:</label>
<input type="number" id="days" placeholder="Enter Number Of Days">
<br>
<input type="button" value="Add" id="add">
<input type="button" value="Substract" id="substract">
<input type="button" value="Calculate" id="calculate">
</form>
<div id="result"></div>

<script>

// Select the input elements we need to use
const startDateInput = document.getElementById("start-date");
const endDateInput = document.getElementById("end-date");
const daysInput = document.getElementById("days");
const resultLabel = document.getElementById("result");
const addButton = document.getElementById("add");
const substractButton = document.getElementById("substract");
const calculateButton = document.getElementById("calculate");
// Helper function to format the date in YYYY-MM-DD format
const formatDate = (date) => {
let d = new Date(date),
month = ''+(d.getMonth()+1),
day = ''+(d.getDate()+1),
year = ''+(d.getFullYear());
if(month.length < 2){
month = '0' + month;
}

if(day.length < 2){
day = '0' + day;
}

return [year, month, day].join('-');

}

// Add click event listeners to the buttons
addButton.addEventListener("click", () => {
// get the number of days from the input field and check if it's a valid number
let days = parseInt(daysInput.value);
if(!days){
resultLabel.innerHTML = "please enter a valid number of days";
return;
}
// get the start date from the input field, add the number of days, and update the input field
let startDate = new Date(startDateInput.value);
startDate.setDate(startDate.getDate() + days);
startDateInput.value = formatDate(startDate);
resultLabel.innerHTML = ""; // clear the error message

});


substractButton.addEventListener("click", () => {
// get the number of days from the input field and check if it's a valid number
let days = parseInt(daysInput.value);
if(!days){
resultLabel.innerHTML = "please enter a valid number of days";
return;
}
// get the start date from the input field, add the number of days, and update the input field
let startDate = new Date(startDateInput.value);
startDate.setDate(startDate.getDate() - days);
startDateInput.value = formatDate(startDate);
resultLabel.innerHTML = ""; // clear the error message

});



calculateButton.addEventListener("click", ()=>{

// get the start and end dates from the input fields
let start = new Date(startDateInput.value);
let end = new Date(endDateInput.value);

// check if the start date is before the end date, and display an error message if not
if(start > end){
resultLabel.innerHTML = "please enter a valid date range";
return;
}

// calculate the difference in days between the start and end dates
let difference = end-start;
let days = Math.round(difference / (1000*60*60*24));
resultLabel.innerHTML = `The difference between the two dates is ${days} days.`;

});


</script>


</body>
</html>




Code Explanation:

this JavaScript code, allows users to add or subtract days from a date, or calculate the difference in days between two dates.

This JavaScript code performs the following actions:

1 - The "Add" button, retrieves the number of days from the input field, checks its validity, and then updates the start date by adding the specified number of days. 
It also clears any prior error messages from the result area..

2 - The "Subtract" button, Similar to the "Add" button, but it subtracts the number of days from the start date.

3 - The "Calculate" button, retrieves start and end dates from input fields, checks for a valid date range, calculates the rounded difference in days between them, and then displays this difference in the result area.



OUTPUT:

JavaScript Date - Add, Subtract and Finding the Difference








Share this

Related Posts

Previous
Next Post »