我如何得到在JavaScript中的两个date之间的差异?
我正在创build一个应用程序,它可以让你用一个时间框架来定义事件。 我想在用户select或更改开始date时自动填写结束date。 然而,我不能完全弄清楚如何获得两次之间的差异,然后如何使用该差异来创build新的结束date。
在JavaScript中,可以通过调用getTime()
方法或仅在数字expression式中使用date,将date转换为epoc以来的毫秒数。
所以为了得到这个差异,只需要减去两个date。
要根据差异创build新date,只需在构造函数中传递毫秒数即可。
var oldBegin = ... var oldEnd = ... var newBegin = ... var newEnd = new Date(newBegin + oldEnd - oldBegin);
这应该只是工作
编辑 :修复@bdukes指出的错误
编辑 :
有关行为的解释, oldBegin
, oldEnd
和newBegin
是Date
实例。 调用操作符+
和-
将触发Javascript自动转换,并自动调用这些对象的valueOf()
原型方法。 碰巧在Date
对象中实现了valueOf()
方法作为对getTime()
的调用。
所以基本上date.getTime() === date.valueOf() === (0 + date) === (+date)
JavaScript完美支持开箱即用的date差异
var msMinute = 60*1000, msDay = 60*60*24*1000, a = new Date(2012, 2, 12, 23, 59, 59), b = new Date("2013 march 12"); console.log(Math.floor((b - a) / msDay) + ' full days between'); console.log(Math.floor(((b - a) % msDay) / msMinute) + ' full minutes between');
现在有些陷阱。 尝试这个:
console.log(a - 10); console.log(a + 10);
因此,如果您有添加数字和date的风险,请将date直接转换为number
。
console.log(a.getTime() - 10); console.log(a.getTime() + 10);
我的拳头示例演示了Date对象的威力,但实际上它似乎是一个定时炸弹
参见JsFiddle DEMO
var date1 = new Date(); var date2 = new Date("2015/07/30 21:59:00"); showDiff(); function showDiff(date1, date2){ var diff = (date2 - date1)/1000; var diff = Math.abs(Math.floor(diff)); var days = Math.floor(diff/(24*60*60)); var leftSec = diff - days * 24*60*60; var hrs = Math.floor(leftSec/(60*60)); var leftSec = leftSec - hrs * 60*60; var min = Math.floor(leftSec/(60)); var leftSec = leftSec - min * 60; document.getElementById("showTime").innerHTML = "You have " + days + " days " + hrs + " hours " + min + " minutes and " + leftSec + " seconds before death."; setTimeout(showDiff,1000); }
为您的HTML代码:
<div id="showTime"></div>
如果你不关心时间组件,可以使用.getDate()
和.setDate()
来设置date部分。
因此,要将您的结束date设置为开始date后的两周,请执行以下操作:
function GetEndDate(startDate) { var endDate = new Date(startDate.getTime()); endDate.setDate(endDate.getDate()+14); return endDate; }
要返回两个date之间的差异(以天为单位),请执行以下操作:
function GetDateDiff(startDate, endDate) { return endDate.getDate() - startDate.getDate(); }
最后,让我们修改第一个函数,以便将第二个参数返回的值作为参数:
function GetEndDate(startDate, days) { var endDate = new Date(startDate.getTime()); endDate.setDate(endDate.getDate() + days); return endDate; }
感谢@ 文森特·罗伯特 ,我结束了使用您的基本示例,但它实际上是newBegin + oldEnd - oldBegin
。 这是简化的最终解决scheme:
// don't update end date if there's already an end date but not an old start date if (!oldEnd || oldBegin) { var selectedDateSpan = 1800000; // 30 minutes if (oldEnd) { selectedDateSpan = oldEnd - oldBegin; } newEnd = new Date(newBegin.getTime() + selectedDateSpan)); }
根据您的需要,这个函数会计算两天之间的差异,并以十进制数返回一个结果。
// This one returns a signed decimal. The sign indicates past or future. this.getDateDiff = function(date1, date2) { return (date1.getTime() - date2.getTime()) / (1000 * 60 * 60 * 24); } // This one always returns a positive decimal. (Suggested by Koen below) this.getDateDiff = function(date1, date2) { return Math.abs((date1.getTime() - date2.getTime()) / (1000 * 60 * 60 * 24)); }
如果使用moment.js,则有一个更简单的解决scheme,它将在一行代码中为您提供天数差异。
moment(endDate).diff(moment(beginDate), 'days');
其他细节可以在moment.js页面find
欢呼声,米格尔
function compare() { var end_actual_time = $('#date3').val(); start_actual_time = new Date(); end_actual_time = new Date(end_actual_time); var diff = end_actual_time-start_actual_time; var diffSeconds = diff/1000; var HH = Math.floor(diffSeconds/3600); var MM = Math.floor(diffSeconds%3600)/60; var formatted = ((HH < 10)?("0" + HH):HH) + ":" + ((MM < 10)?("0" + MM):MM) getTime(diffSeconds); } function getTime(seconds) { var days = Math.floor(leftover / 86400); //how many seconds are left leftover = leftover - (days * 86400); //how many full hours fits in the amount of leftover seconds var hours = Math.floor(leftover / 3600); //how many seconds are left leftover = leftover - (hours * 3600); //how many minutes fits in the amount of leftover seconds var minutes = leftover / 60; //how many seconds are left //leftover = leftover - (minutes * 60); alert(days + ':' + hours + ':' + minutes); }
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') }
替代修改扩展代码
showDiff(); function showDiff(){ var date1 = new Date("2013/01/18 06:59:00"); var date2 = new Date(); //Customise date2 for your required future time var diff = (date2 - date1)/1000; var diff = Math.abs(Math.floor(diff)); var years = Math.floor(diff/(365*24*60*60)); var leftSec = diff - years * 365*24*60*60; var month = Math.floor(leftSec/((365/12)*24*60*60)); var leftSec = leftSec - month * (365/12)*24*60*60; var days = Math.floor(leftSec/(24*60*60)); var leftSec = leftSec - days * 24*60*60; var hrs = Math.floor(leftSec/(60*60)); var leftSec = leftSec - hrs * 60*60; var min = Math.floor(leftSec/(60)); var leftSec = leftSec - min * 60; document.getElementById("showTime").innerHTML = "You have " + years + " years "+ month + " month " + days + " days " + hrs + " hours " + min + " minutes and " + leftSec + " seconds the life time has passed."; setTimeout(showDiff,1000); }
<html> <head> <script> function dayDiff() { var start = document.getElementById("datepicker").value; var end= document.getElementById("date_picker").value; var oneDay = 24*60*60*1000; var firstDate = new Date(start); var secondDate = new Date(end); var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay))); document.getElementById("leave").value =diffDays ; } </script> </head> <body> <input type="text" name="datepicker"value=""/> <input type="text" name="date_picker" onclick="function dayDiff()" value=""/> <input type="text" name="leave" value=""/> </body> </html>
这段代码填写了学习年限,当你input研究的开始date和结束date(限定适应date),并检查是否持续时间less于一年,如果是的话,警告消息记住有三个input元素第一个txtFromQualifDate
第二个txtQualifDate
和第三个txtStudyYears
它会显示分数的年数的结果
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; } }
如果您使用Date对象,然后在两个date中使用getTime()
函数,它将自1970年1月1日起以数值forms给出它们各自的时间。 然后你可以得到这些数字之间的差异。
如果没有帮助,请查看完整的文档: http : //www.w3schools.com/jsref/jsref_obj_date.asp