Determining the length of a year based on user-provided date input in a textbox

How can I show the duration in years? After a date is entered into a text box, the total number of years (duration) should be displayed in the next field. For example, if a user enters 09/11/2015, it should display as 0.5 as the value by comparing it to today's date. I am currently using the following script:

function calculateDuration()
{
   obj = document.getElementById("Date");
        if (obj != null) {
            if (obj.value != "") {
                var year = obj.value.split("/")[2];
                var today = new Date();
                if (year > today.getFullYear()) {
                    alert("Invalid Year");
                    document.getElementById("Date").value = "";
                    document.getElementById("year").value = "";
                }
                else {
               
         document .getElementById("year").value = today.getFullYear() - year;
               } }
            }
}

`

Answer №1

function calculateDays(){
var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var firstDate = new Date(2016,04,12);
var secondDate = new Date(2016,04,25);

var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));

alert(diffDays+" Day(s)");
//document.getElementById('test').innerHTML=diffDays;

}
<button onClick="calculateDays()">
Click Here
</button>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be the reason behind getting a useLayoutEffect error when using renderToString to render a Material-UI component?

Currently, I am utilizing React version 16.12.0 along with @MaterialUI/core version 4.8.1. The challenge I am facing involves creating a custom icon for a React Leaflet Marker. The icon in question is a Fab component sourced from Material-UI. In order to ...

An exception was thrown during the initialization of "Azure.Core.Pipeline.HttpClientTransport"

Encountering the following exception while attempting to access Azure Key Vault. The initialization of "Azure.Core.Pipeline.HttpClientTransport" resulted in an exception.' FileLoadException: Loading this assembly would generate a different grant se ...

Having trouble with the Twitter share count URL - seeking out other options

Previously, I utilized the following Javascript function to retrieve the Twitter share count for a URL. Unfortunately, Twitter has discontinued providing the share count. Is there a more effective alternative available? // Twitter Shares Count $.getJSON ...

Downloading a PDF file received from a Django view using JavaScript and jQuery

I have a celery task that creates PDF files on the click of a button. When the button is clicked, the JavaScript side will keep checking until the task is done, and when it is, it will download the file. Some recursion should do the trick: $(".getPdf").o ...

Activating the click event by clicking or tapping on the touch screen

HTML: <footer> <a href="#"><div class="footbut" id="chooseFile" onclick=""> <div class="done2 gradGreen" data-bind="visible: picsCount(objectInRoute())>0"> <div class="typcn ...

Generating JSON on-the-fly with fluctuating keys and values in conjunction with Express JS

When I fetch an API into my Express server, the data comes in the form of JSON key-value pairs within an array. [{ "quality": "best", "url": "https://someurlhere.example/?someparameters" }, { "quality": ...

What is the best way to determine if certain rows of data have been successfully loaded when working with Ext.data.operation and an ajaxProxy?

Here is the provided code snippet: Ext.define('Book', { extend: 'Ext.data.Model', fields: [ {name: 'id', type: 'int'}, {name: 'title', type: 'string'}, {name: &apo ...

Can Typescript React Components be created separately for integration into older html applications?

Exploring methods to transition away from outdated front ends by utilizing micro front ends. If I have a React Component Library with Typescript, is it viable to construct the components one by one in order to import them into the existing html/js applica ...

A guide on getting the POST method to function with router.post in ExpressJS

I'm currently learning how to create a web application by following a helpful tutorial. The main focus of the app is on creating posts and allowing users to comment on them. I have successfully set up the POST method for creating posts, but I am facin ...

Is the length of a complex match in Angular JS ng-if and ng-repeat greater than a specified value?

In my code, there is an ng-repeat that generates a table based on one loop, and within each row, another cell is populated based on a different loop: <tbody> <tr ng-repeat="r in roles | limitTo: 30"> <td>{{r.name}}</td> ...

Incorporating and designing a side button using jQuery Mobile

I'm working on adding a button to the left side of the screen that is round (but not necessarily) and partially visible, with a visually appealing design. This button will allow users to open a side menu panel. Below is the HTML code for the button: ...

Verify whether the input checkbox is blank with the help of JavaScript

I have created a dropdown filter with checkboxes for gender and category selection. Now, I want to ensure that the user selects at least one checkbox from each section (gender and category). However, I am struggling to figure out how to determine if a chec ...

Switch a Laravel Collection or Array into a JavaScript Array

Is there a way to transfer data from Laravel to a JavaScript array? I have extracted the data from my AppServiceProvider and decoded it using json_decode, as shown below: View::composer('*', function($view) { $users = Users::all(); $view-& ...

Transforming ASP.NET MVC IEnumerable view model into a JSON array of elements

My goal is to develop a dynamic calendar in ASP.NET MVC that pulls event data from a database to populate it. Right now, the calendar is set up to read a json array of objects, but I am facing an issue with converting my ViewModel data into a format that t ...

Can a javascript variable be integrated into JRoute() function?

function getProduct(category) { document.star.action = '<?php echo JRoute::_('index.php?option=com_virtuemart&view=category&virtuemart_category_id='+ category) ?>'; document.getElementById('star').submit( ...

What is the best way to display a unique modal on every tab?

I'm facing an issue where I am attempting to trigger a modal on each tab item, however the modal only opens on the initial tab. Clicking on any other item results in the modal opening on the first tab instead. Additionally, when I add new items, I am ...

Guide on how to navigate to a different page while making a request in ASP.NET

I have a standard asp.net page containing multiple buttons. I would like to add one button labeled Stop Request, which, when clicked, refreshes the page regardless of which other button the user has clicked previously. Here is an example of how I envision ...

Steps to fix ESlint warning: Avoid using assignment in return Statement (no-return-assign)

In my React application, I am utilizing the package found at https://github.com/appleboy/react-recaptcha to create a Recaptcha component. Below is an image of what the component looks like, along with an eslint warning: https://i.sstatic.net/ZleMK.png Th ...

What are some strategies for enhancing state management in ReactJS?

Currently, I am retrieving information via an API and storing it in the state. This information needs to be filtered based on what I type into an input field. However, I have encountered an issue where if I delete a letter from the input, I am unable to re ...

The navbar's background sections have various colors

Struggling to grasp React? Want to create a partially transparent Bootstrap navbar and customize the color, but encountering inconsistency due to the main background color setting. How can this be resolved? My App: function App() { return ( < ...