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

前端 未结 16 2355
北海茫月
北海茫月 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:56

    In JavaScript, dates can be transformed to the number of milliseconds since the epoc by calling the getTime() method or just using the date in a numeric expression.

    So to get the difference, just subtract the two dates.

    To create a new date based on the difference, just pass the number of milliseconds in the constructor.

    var oldBegin = ...
    var oldEnd = ...
    var newBegin = ...
    
    var newEnd = new Date(newBegin + oldEnd - oldBegin);
    

    This should just work

    EDIT: Fixed bug pointed by @bdukes

    EDIT:

    For an explanation of the behavior, oldBegin, oldEnd, and newBegin are Date instances. Calling operators + and - will trigger Javascript auto casting and will automatically call the valueOf() prototype method of those objects. It happens that the valueOf() method is implemented in the Date object as a call to getTime().

    So basically: date.getTime() === date.valueOf() === (0 + date) === (+date)

    0 讨论(0)
  • 2020-11-22 03:58
    function checkdate() {
        var indate = new Date()
        indate.setDate(dat)
        indate.setMonth(mon - 1)
        indate.setFullYear(year)
    
        var one_day = 1000 * 60 * 60 * 24
        var diff = Math.ceil((indate.getTime() - now.getTime()) / (one_day))
        var str = diff + " days are remaining.."
        document.getElementById('print').innerHTML = str.fontcolor('blue')
    }
    
    0 讨论(0)
  • 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;
            }
        }
    
    0 讨论(0)
  • 2020-11-22 03:59

    Below code will return the days left from today to futures date.

    Dependencies: jQuery and MomentJs.

    var getDaysLeft = function (date) {
      var today = new Date();
      var daysLeftInMilliSec = Math.abs(new Date(moment(today).format('YYYY-MM-DD')) - new Date(date));
      var daysLeft = daysLeftInMilliSec / (1000 * 60 * 60 * 24);   
      return daysLeft;
    };
    
    getDaysLeft('YYYY-MM-DD');
    
    0 讨论(0)
  • 2020-11-22 04:00
    var getDaysLeft = function (date1, date2) {
       var daysDiffInMilliSec = Math.abs(new Date(date1) - new Date(date2));
       var daysLeft = daysDiffInMilliSec / (1000 * 60 * 60 * 24);   
       return daysLeft;
    };
    var date1='2018-05-18';
    var date2='2018-05-25';
    var dateDiff = getDaysLeft(date1, date2);
    console.log(dateDiff);
    
    0 讨论(0)
  • 2020-11-22 04:01

    THIS IS WHAT I DID ON MY SYSTEM.

    var startTime=("08:00:00").split(":");
    var endTime=("16:00:00").split(":");
    var HoursInMinutes=((parseInt(endTime[0])*60)+parseInt(endTime[1]))-((parseInt(startTime[0])*60)+parseInt(startTime[1]));
    console.log(HoursInMinutes/60);
    
    0 讨论(0)
提交回复
热议问题