<p>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.  I can't quite figure out, however, how to get the difference between the two times, and then how to create a new end Date using that difference.</p>

[{'answer_id': 41960, 'author': 'Vincent Robert', 'author_id': 268, 'author_profile': 'https://Stackoverflow.com/users/268', 'pm_score': 7, 'selected': True, 'text': '<p>In JavaScript, dates can be transformed to the number of milliseconds since the epoc by calling the <code>getTime()</code> method <strong>or</strong> just using the date in a numeric expression.</p>\n\n<p>So to get the difference, just subtract the two dates.</p>\n\n<p>To create a new date based on the difference, just pass the number of milliseconds in the constructor.</p>\n\n<pre><code>var oldBegin = ...\nvar oldEnd = ...\nvar newBegin = ...\n\nvar newEnd = new Date(newBegin + oldEnd - oldBegin);\n</code></pre>\n\n<p>This should just work</p>\n\n<p><strong>EDIT</strong>: Fixed bug pointed by @bdukes</p>\n\n<p><strong>EDIT</strong>: </p>\n\n<p>For an explanation of the behavior, <code>oldBegin</code>, <code>oldEnd</code>, and <code>newBegin</code> are <code>Date</code> instances. Calling operators <code>+</code> and <code>-</code> will trigger Javascript auto casting and will automatically call the <code>valueOf()</code> prototype method of those objects. It happens that the <code>valueOf()</code> method is implemented in the <code>Date</code> object as a call to <code>getTime()</code>.</p>\n\n<p>So basically: <code>date.getTime() === date.valueOf() === (0 + date) === (+date)</code></p>\n'}, {'answer_id': 41966, 'author': 'Aaron', 'author_id': 2628, 'author_profile': 'https://Stackoverflow.com/users/2628', 'pm_score': 0, 'selected': False, 'text': '<p>If you use Date objects and then use the <code>getTime()</code> function for both dates it will give you their respective times since Jan 1, 1970 in a number value. You can then get the difference between these numbers. </p>\n\n<p>If that doesn\'t help you out, check out the complete documentation: <a href="http://www.w3schools.com/jsref/jsref_obj_date.asp" rel="nofollow noreferrer">http://www.w3schools.com/jsref/jsref_obj_date.asp</a></p>\n'}, {'answer_id': 41974, 'author': 'Joel Coehoorn', 'author_id': 3043, 'author_profile': 'https://Stackoverflow.com/users/3043', 'pm_score': 3, 'selected': False, 'text': "<p>If you don't care about the time component, you can use <code>.getDate()</code> and <code>.setDate()</code> to just set the date part.</p>\n\n<p>So to set your end date to 2 weeks after your start date, do something like this:</p>\n\n<pre><code>function GetEndDate(startDate)\n{\n    var endDate = new Date(startDate.getTime());\n    endDate.setDate(endDate.getDate()+14);\n    return endDate;\n}\n</code></pre>\n\n<p>To return the difference (in days) between two dates, do this:</p>\n\n<pre><code>function GetDateDiff(startDate, endDate)\n{\n    return endDate.getDate() - startDate.getDate();\n}\n</code></pre>\n\n<p>Finally, let's modify the first function so it can take the value returned by 2nd as a parameter:</p>\n\n<pre><code>function GetEndDate(startDate, days)\n{\n    var endDate = new Date(startDate.getTime());\n    endDate.setDate(endDate.getDate() + days);\n    return endDate;\n}\n</code></pre>\n"}, {'answer_id': 42086, 'author': 'bdukes', 'author_id': 2688, 'author_profile': 'https://Stackoverflow.com/users/2688', 'pm_score': 2, 'selected': False, 'text': '<p>Thanks @<a href="https://stackoverflow.com/questions/41948/how-do-i-get-the-difference-between-two-dates-in-javascript#41960">Vincent Robert</a>, I ended up using your basic example, though it\'s actually <code>newBegin + oldEnd - oldBegin</code>.  Here\'s the simplified end solution:</p>\n\n<pre><code>    // don\'t update end date if there\'s already an end date but not an old start date\n    if (!oldEnd || oldBegin) {\n        var selectedDateSpan = 1800000; // 30 minutes\n        if (oldEnd) {\n            selectedDateSpan = oldEnd - oldBegin;\n        }\n\n       newEnd = new Date(newBegin.getTime() + selectedDateSpan));\n    }\n</code></pre>\n'}, {'answer_id': 5056705, 'author': 'hiren gamit', 'author_id': 625179, 'author_profile': 'https://Stackoverflow.com/users/625179', 'pm_score': -1, 'selected': False, 'text': '<pre><code>function checkdate() {\n    var indate = new Date()\n    indate.setDate(dat)\n    indate.setMonth(mon - 1)\n    indate.setFullYear(year)\n\n    var one_day = 1000 * 60 * 60 * 24\n    var diff = Math.ceil((indate.getTime() - now.getTime()) / (one_day))\n    var str = diff + " days are remaining.."\n    document.getElementById(\'print\').innerHTML = str.fontcolor(\'blue\')\n}\n</code></pre>\n'}, {'answer_id': 10409160, 'author': 'shareef', 'author_id': 944593, 'author_profile': 'https://Stackoverflow.com/users/944593', 'pm_score': 0, 'selected': False, 'text': '<p>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 \ntake in mind there are three input elements the first <code>txtFromQualifDate</code> and second <code>txtQualifDate</code> and third <code>txtStudyYears</code></p>\n\n<p>it will show result of number of years with fraction</p>\n\n<pre><code>function getStudyYears()\n    {\n        if(document.getElementById(\'txtFromQualifDate\').value != \'\' &amp;&amp; document.getElementById(\'txtQualifDate\').value != \'\')\n        {\n            var d1 = document.getElementById(\'txtFromQualifDate\').value;\n\n            var d2 = document.getElementById(\'txtQualifDate\').value;\n\n            var one_day=1000*60*60*24;\n\n            var x = d1.split("/");\n            var y = d2.split("/");\n\n            var date1=new Date(x[2],(x[1]-1),x[0]);\n\n            var date2=new Date(y[2],(y[1]-1),y[0])\n\n            var dDays = (date2.getTime()-date1.getTime())/one_day;\n\n            if(dDays &lt; 365)\n            {\n                alert("the date between start study and graduate must not be less than a year !");\n\n                document.getElementById(\'txtQualifDate\').value = "";\n                document.getElementById(\'txtStudyYears\').value = "";\n\n                return ;\n            }\n\n            var dMonths = Math.ceil(dDays / 30);\n\n            var dYears = Math.floor(dMonths /12) + "." + dMonths % 12;\n\n            document.getElementById(\'txtStudyYears\').value = dYears;\n        }\n    }\n</code></pre>\n'}, {'answer_id': 10536394, 'author': 'sparkyspider', 'author_id': 578318, 'author_profile': 'https://Stackoverflow.com/users/578318', 'pm_score': 2, 'selected': False, 'text': '<p>Depending on your needs, this function will calculate the difference between the 2 days, and return a result in days decimal.</p>\n\n<pre><code>// This one returns a signed decimal. The sign indicates past or future.\n\nthis.getDateDiff = function(date1, date2) {\n    return (date1.getTime() - date2.getTime()) / (1000 * 60 * 60 * 24);\n}\n\n// This one always returns a positive decimal. (Suggested by Koen below)\n\nthis.getDateDiff = function(date1, date2) {\n    return Math.abs((date1.getTime() - date2.getTime()) / (1000 * 60 * 60 * 24));\n}\n</code></pre>\n'}, {'answer_id': 15810692, 'author': 'Dan', 'author_id': 139361, 'author_profile': 'https://Stackoverflow.com/users/139361', 'pm_score': 5, 'selected': False, 'text': '<p>JavaScript perfectly supports date difference out of the box</p>\n<p><a href="https://jsfiddle.net/b9chris/v5twbe3h/" rel="nofollow noreferrer">https://jsfiddle.net/b9chris/v5twbe3h/</a></p>\n<pre><code>var msMinute = 60*1000, \n    msDay = 60*60*24*1000,\n    a = new Date(2012, 2, 12, 23, 59, 59),\n    b = new Date(&quot;2013 march 12&quot;);\n\n\nconsole.log(Math.floor((b - a) / msDay) + \' full days between\'); // 364\nconsole.log(Math.floor(((b - a) % msDay) / msMinute) + \' full minutes between\'); // 0\n</code></pre>\n<hr />\n<p>Now some pitfalls. Try this:</p>\n<pre><code>console.log(a - 10); // 1331614798990\nconsole.log(a + 10); // mixed string\n</code></pre>\n<p>So if you have risk of adding a number and Date, convert Date to <code>number</code> directly.</p>\n<pre><code>console.log(a.getTime() - 10); // 1331614798990\nconsole.log(a.getTime() + 10); // 1331614799010\n</code></pre>\n<p>My fist example demonstrates the power of Date object but it actually appears to be a time bomb</p>\n'}, {'answer_id': 20002054, 'author': 'dheerendra', 'author_id': 2927163, 'author_profile': 'https://Stackoverflow.com/users/2927163', 'pm_score': 1, 'selected': False, 'text': '<pre><code>function compare()\n{\n  var end_actual_time    = $(\'#date3\').val();\n\n  start_actual_time = new Date();\n  end_actual_time = new Date(end_actual_time);\n\n  var diff = end_actual_time-start_actual_time;\n\n  var diffSeconds = diff/1000;\n  var HH = Math.floor(diffSeconds/3600);\n  var MM = Math.floor(diffSeconds%3600)/60;\n\n  var formatted = ((HH &lt; 10)?("0" + HH):HH) + ":" + ((MM &lt; 10)?("0" + MM):MM)\n  getTime(diffSeconds);\n}\nfunction getTime(seconds) {\n  var days = Math.floor(leftover / 86400);\n\n  //how many seconds are left\n  leftover = leftover - (days * 86400);\n\n  //how many full hours fits in the amount of leftover seconds\n  var hours = Math.floor(leftover / 3600);\n\n  //how many seconds are left\n  leftover = leftover - (hours * 3600);\n\n  //how many minutes fits in the amount of leftover seconds\n  var minutes = leftover / 60;\n\n  //how many seconds are left\n  //leftover = leftover - (minutes * 60);\n  alert(days + \':\' + hours + \':\' + minutes);\n}\n</code></pre>\n'}, {'answer_id': 25042075, 'author': 'tika', 'author_id': 2988919, 'author_profile': 'https://Stackoverflow.com/users/2988919', 'pm_score': 3, 'selected': False, 'text': '<p><strong><em><a href="http://jsfiddle.net/vvGPQ/1/" rel="noreferrer">See JsFiddle DEMO</a></em></strong></p>\n\n<pre><code>    var date1 = new Date();    \n    var date2 = new Date("2025/07/30 21:59:00");\n    //Customise date2 for your required future time\n\n    showDiff();\n\nfunction showDiff(date1, date2){\n\n    var diff = (date2 - date1)/1000;\n    diff = Math.abs(Math.floor(diff));\n\n    var days = Math.floor(diff/(24*60*60));\n    var leftSec = diff - days * 24*60*60;\n\n    var hrs = Math.floor(leftSec/(60*60));\n    var leftSec = leftSec - hrs * 60*60;\n\n    var min = Math.floor(leftSec/(60));\n    var leftSec = leftSec - min * 60;\n\n    document.getElementById("showTime").innerHTML = "You have " + days + " days " + hrs + " hours " + min + " minutes and " + leftSec + " seconds before death.";\n\nsetTimeout(showDiff,1000);\n}\n</code></pre>\n\n<p>for your HTML Code:</p>\n\n<pre><code>&lt;div id="showTime"&gt;&lt;/div&gt;\n</code></pre>\n'}, {'answer_id': 28616175, 'author': 'NovaYear', 'author_id': 556986, 'author_profile': 'https://Stackoverflow.com/users/556986', 'pm_score': 1, 'selected': False, 'text': '<p>alternative modificitaion extended code..</p>\n\n<p><a href="http://jsfiddle.net/vvGPQ/48/" rel="nofollow">http://jsfiddle.net/vvGPQ/48/</a></p>\n\n<pre><code>showDiff();\n\nfunction showDiff(){\nvar date1 = new Date("2013/01/18 06:59:00");   \nvar date2 = new Date();\n//Customise date2 for your required future time\n\nvar diff = (date2 - date1)/1000;\nvar diff = Math.abs(Math.floor(diff));\n\nvar years = Math.floor(diff/(365*24*60*60));\nvar leftSec = diff - years * 365*24*60*60;\n\nvar month = Math.floor(leftSec/((365/12)*24*60*60));\nvar leftSec = leftSec - month * (365/12)*24*60*60;    \n\nvar days = Math.floor(leftSec/(24*60*60));\nvar leftSec = leftSec - days * 24*60*60;\n\nvar hrs = Math.floor(leftSec/(60*60));\nvar leftSec = leftSec - hrs * 60*60;\n\nvar min = Math.floor(leftSec/(60));\nvar leftSec = leftSec - min * 60;\n\n\n\n\ndocument.getElementById("showTime").innerHTML = "You have " + years + " years "+ month + " month " + days + " days " + hrs + " hours " + min + " minutes and " + leftSec + " seconds the life time has passed.";\n\nsetTimeout(showDiff,1000);\n}\n</code></pre>\n'}, {'answer_id': 34782685, 'author': 'Sukanya Suku', 'author_id': 5681934, 'author_profile': 'https://Stackoverflow.com/users/5681934', 'pm_score': 0, 'selected': False, 'text': '<pre><code>&lt;html&gt;\n&lt;head&gt;\n&lt;script&gt;\nfunction dayDiff()\n{\n     var start = document.getElementById("datepicker").value;\n     var end= document.getElementById("date_picker").value;\n     var oneDay = 24*60*60*1000; \n     var firstDate = new Date(start);\n     var secondDate = new Date(end);    \n     var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));\n    document.getElementById("leave").value =diffDays ;\n }\n&lt;/script&gt;\n&lt;/head&gt;\n&lt;body&gt;\n&lt;input type="text" name="datepicker"value=""/&gt;\n&lt;input type="text" name="date_picker" onclick="function dayDiff()" value=""/&gt;\n&lt;input type="text" name="leave" value=""/&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n'}, {'answer_id': 37532797, 'author': 'Miguel Guardo', 'author_id': 5739841, 'author_profile': 'https://Stackoverflow.com/users/5739841', 'pm_score': 2, 'selected': False, 'text': '<p>If using moment.js, there is a simpler solution, which will give you the difference in days in one single line of code.</p>\n\n<pre><code>moment(endDate).diff(moment(beginDate), \'days\');\n</code></pre>\n\n<p>Additional details can be found in the <a href="http://momentjs.com/docs/#/displaying/difference/" rel="nofollow">moment.js page</a></p>\n\n<p>Cheers,\nMiguel</p>\n'}, {'answer_id': 49576078, 'author': 'Vin S', 'author_id': 9573544, 'author_profile': 'https://Stackoverflow.com/users/9573544', 'pm_score': 1, 'selected': False, 'text': "<p><strong>Below code  will return the days left from today to futures date.</strong></p>\n\n<p>Dependencies: <strong>jQuery and MomentJs.</strong></p>\n\n<pre><code>var getDaysLeft = function (date) {\n  var today = new Date();\n  var daysLeftInMilliSec = Math.abs(new Date(moment(today).format('YYYY-MM-DD')) - new Date(date));\n  var daysLeft = daysLeftInMilliSec / (1000 * 60 * 60 * 24);   \n  return daysLeft;\n};\n\ngetDaysLeft('YYYY-MM-DD');\n</code></pre>\n"}, {'answer_id': 50414819, 'author': 'Vin S', 'author_id': 9573544, 'author_profile': 'https://Stackoverflow.com/users/9573544', 'pm_score': 0, 'selected': False, 'text': "<pre><code>var getDaysLeft = function (date1, date2) {\n   var daysDiffInMilliSec = Math.abs(new Date(date1) - new Date(date2));\n   var daysLeft = daysDiffInMilliSec / (1000 * 60 * 60 * 24);   \n   return daysLeft;\n};\nvar date1='2018-05-18';\nvar date2='2018-05-25';\nvar dateDiff = getDaysLeft(date1, date2);\nconsole.log(dateDiff);\n</code></pre>\n"}, {'answer_id': 50508313, 'author': 'Sean Cortez', 'author_id': 8750004, 'author_profile': 'https://Stackoverflow.com/users/8750004', 'pm_score': -1, 'selected': False, 'text': '<p>THIS IS WHAT I DID ON MY SYSTEM. </p>\n\n<pre><code>var startTime=("08:00:00").split(":");\nvar endTime=("16:00:00").split(":");\nvar HoursInMinutes=((parseInt(endTime[0])*60)+parseInt(endTime[1]))-((parseInt(startTime[0])*60)+parseInt(startTime[1]));\nconsole.log(HoursInMinutes/60);\n</code></pre>\n'}, {'answer_id': 72967699, 'author': 'Liam Pillay', 'author_id': 11404295, 'author_profile': 'https://Stackoverflow.com/users/11404295', 'pm_score': 0, 'selected': False, 'text': '<p>To get the date difference in milliseconds between two dates:</p>\n<pre class="lang-js prettyprint-override"><code>var diff = Math.abs(date1 - date2);\n</code></pre>\n<p>I\'m not sure what you mean by converting the difference back into a date though.</p>\n'}]
['https://Stackoverflow.com/questions/41948', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2688/']