This JavaScript code snippet allows you to calculate the elapsed time between two dates in days. It uses a simple form to collect the start date and end date from the user and then uses the JS function to calculate the difference. The result is displayed in a span element on the page.
You can integrate this code into your web projects for instant date difference calculations. It simplifies date-related tasks and streamlines data presentation on your website.
How to Elapsed Time Between Two Dates In JavaScript
1. First, copy the HTML structure to create an intuitive date input interface.
<header> <h1>Date Calculator</h1> <p>How many days are there between two dates?</p> <p>(Change a date to automatically calculate the difference)</p> </header> <div> <form> <label>Start Date: </label> <input type="date" name="start_date"> <label>End Date: </label> <input type="date" name="end_date"> </form> <p> Time elapsed: <span class="date_span"></span> </p> </div>
2. Now, add the following CSS code to your project to style the basic interface for the date calculator. Feel free to customize the CSS to match your website’s theme. Adjust fonts, colors, and layout to seamlessly integrate the Date Calculator into your design. (Optional)
body{ flex-direction: column !important; background: linear-gradient(to right, #c9d6ff, #e2e2e2) !important; line-height: 2.3; } h1 { font-family: 'Arial', 'Verdana', sans-serif; font-size: 2.5em; font-weight: bold; text-align: center; } header > p { font-family: 'Arial', 'Verdana', sans-serif; text-align: center; } div { text-align: center; border: 0.1em solid #000; }
3. Finally, add the following JavaScript code to your website/app project. As users input or change dates, the JavaScript code dynamically computes and displays the elapsed time in days.
let span = document.querySelector(".date_span"); let dateInputs = document.querySelectorAll('input'); dateInputs[1].valueAsDate = new Date(); function calculateElapse() { if (!isNaN(dateInputs[0].valueAsNumber) && !isNaN(dateInputs[1].valueAsDate)) { // I don't think this is necessary, but it's robust. span.textContent = "" + ((dateInputs[1].valueAsDate - dateInputs[0].valueAsDate) / (24 * 60 * 60 * 1000)) + " day(s)"; } } dateInputs.forEach(elements => elements.addEventListener('change', calculateElapse));
That’s all! hopefully, you have successfully created a functionality for elapsed time between two dates on your website. If you have any questions or suggestions, feel free to comment below.
Similar Code Snippets:
I code and create web elements for amazing people around the world. I like work with new people. New people new Experiences.
I truly enjoy what I’m doing, which makes me more passionate about web development and coding. I am always ready to do challenging tasks whether it is about creating a custom CMS from scratch or customizing an existing system.