How do I get the difference between two Dates in JavaScript?

前端 未结 16 2383
北海茫月
北海茫月 2020-11-22 03:03

I\'m creating an application which lets you define events with a time frame. I want to automatically fill in the end date when the user selects or changes the start date.

16条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 03:58

    this code fills the duration of study years when you input the start date and end date(qualify accured date) of study and check if the duration less than a year if yes the alert a message take in mind there are three input elements the first txtFromQualifDate and second txtQualifDate and third txtStudyYears

    it will show result of number of years with fraction

    function getStudyYears()
        {
            if(document.getElementById('txtFromQualifDate').value != '' && document.getElementById('txtQualifDate').value != '')
            {
                var d1 = document.getElementById('txtFromQualifDate').value;
    
                var d2 = document.getElementById('txtQualifDate').value;
    
                var one_day=1000*60*60*24;
    
                var x = d1.split("/");
                var y = d2.split("/");
    
                var date1=new Date(x[2],(x[1]-1),x[0]);
    
                var date2=new Date(y[2],(y[1]-1),y[0])
    
                var dDays = (date2.getTime()-date1.getTime())/one_day;
    
                if(dDays < 365)
                {
                    alert("the date between start study and graduate must not be less than a year !");
    
                    document.getElementById('txtQualifDate').value = "";
                    document.getElementById('txtStudyYears').value = "";
    
                    return ;
                }
    
                var dMonths = Math.ceil(dDays / 30);
    
                var dYears = Math.floor(dMonths /12) + "." + dMonths % 12;
    
                document.getElementById('txtStudyYears').value = dYears;
            }
        }
    

提交回复
热议问题