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.
我正在创建一个应用程序,它允许您定义具有时间框架的事件。我想在用户选择或更改开始日期时自动填写结束日期。但是,我不太清楚如何得到这两次时间之间的差异,以及如何使用这种差异创建新的结束日期。
16 个解决方案
#1
65
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.
在JavaScript中,日期可以通过调用getTime()方法或者只是在数字表达式中使用日期,来转换为自epoc以来的毫秒数。
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
修正了@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()
.
对于行为的解释,oldBegin、oldEnd和newBegin是日期实例。调用操作符+和-将触发Javascript自动转换,并自动调用这些对象的valueOf()原型方法。碰巧valueOf()方法在Date对象中实现为对getTime()的调用。
So basically: date.getTime() === date.valueOf() === (0 + date) === (+date)
基本上,date.getTime() == date.valueOf() ==(0 +日期)===(+日期)==(+日期)
#2
20
JavaScript perfectly supports date difference out of the box
JavaScript完全支持日期差异。
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');
Now some pitfalls. Try this:
现在一些隐患。试试这个:
console.log(a - 10);
console.log(a + 10);
So if you have risk of adding a number and Date, convert Date to number
directly.
所以如果你有增加数字和日期的风险,直接把日期转换成数字。
console.log(a.getTime() - 10);
console.log(a.getTime() + 10);
My fist example demonstrates the power of Date object but it actually appears to be a time bomb
我的第一个例子展示了日期对象的力量,但它实际上似乎是一个定时炸弹
#3
5
看到JsFiddle演示
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);
}
for your HTML Code:
为你的HTML代码:
<div id="showTime"></div>
#4
4
If you don't care about the time component, you can use .getDate()
and .setDate()
to just set the date part.
如果不关心时间组件,可以使用. getdate()和. setdate()来设置日期部分。
So to set your end date to 2 weeks after your start date, do something like this:
因此,要将你的截止日期设为开始日期后的两周,可以这样做:
function GetEndDate(startDate)
{
var endDate = new Date(startDate.getTime());
endDate.setDate(endDate.getDate()+14);
return endDate;
}
To return the difference (in days) between two dates, do this:
要返回两个日期之间的差异(以天为单位),请执行以下操作:
function GetDateDiff(startDate, endDate)
{
return endDate.getDate() - startDate.getDate();
}
Finally, let's modify the first function so it can take the value returned by 2nd as a parameter:
最后,我们修改第一个函数,使其以2返回的值为参数:
function GetEndDate(startDate, days)
{
var endDate = new Date(startDate.getTime());
endDate.setDate(endDate.getDate() + days);
return endDate;
}
#5
3
Thanks @Vincent Robert, I ended up using your basic example, though it's actually newBegin + oldEnd - oldBegin
. Here's the simplified end solution:
感谢@Vincent Robert,我最终使用了您的基本示例,尽管它实际上是newBegin + oldEnd - oldBegin。下面是简化的最终解决方案:
// 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));
}
#6
2
Depending on your needs, this function will calculate the difference between the 2 days, and return a result in days decimal.
根据您的需要,这个函数将计算这2天之间的差值,并返回一个以days decimal为单位的结果。
// 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));
}
#7
2
If using moment.js, there is a simpler solution, which will give you the difference in days in one single line of code.
如果使用的时刻。js,有一种更简单的解决方案,它将在一行代码中提供不同的天数。
moment(endDate).diff(moment(beginDate), 'days');
Additional details can be found in the moment.js page
现在可以找到更多的细节。js页面
Cheers, Miguel
米盖尔,干杯
#8
1
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);
}
#9
0
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')
}
#10
0
alternative modificitaion extended code..
替代modificitaion扩展代码. .
http://jsfiddle.net/vvGPQ/48/
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);
}
#11
0
<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>
#12
0
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
这段代码填充研究多年的持续时间当你输入开始日期和结束日期(资格雷达波日期)的研究和检查时间不到一年如果有警报消息先记住有三个输入元素txtFromQualifDate和第二txtQualifDate第三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;
}
}
#13
0
If you use Date objects and then use the getTime()
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.
如果您使用Date对象,然后对这两个日期使用getTime()函数,它将给出一个数字值,从1970年1月1日开始,它们各自的时间。你可以得到这些数字之间的差值。
If that doesn't help you out, check out the complete documentation: http://www.w3schools.com/jsref/jsref_obj_date.asp
如果这对您没有帮助,请查看完整的文档:http://www.w3schools.com/jsref/jsref_obj_date.asp
#14
0
Below code will return the days left from today to futures date.
以下代码将返回从今天到期货的剩余天数。
Dependencies: jQuery and MomentJs.
依赖性:jQuery和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');
#15
0
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);
#16
0
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);
#1
65
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.
在JavaScript中,日期可以通过调用getTime()方法或者只是在数字表达式中使用日期,来转换为自epoc以来的毫秒数。
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
修正了@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()
.
对于行为的解释,oldBegin、oldEnd和newBegin是日期实例。调用操作符+和-将触发Javascript自动转换,并自动调用这些对象的valueOf()原型方法。碰巧valueOf()方法在Date对象中实现为对getTime()的调用。
So basically: date.getTime() === date.valueOf() === (0 + date) === (+date)
基本上,date.getTime() == date.valueOf() ==(0 +日期)===(+日期)==(+日期)
#2
20
JavaScript perfectly supports date difference out of the box
JavaScript完全支持日期差异。
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');
Now some pitfalls. Try this:
现在一些隐患。试试这个:
console.log(a - 10);
console.log(a + 10);
So if you have risk of adding a number and Date, convert Date to number
directly.
所以如果你有增加数字和日期的风险,直接把日期转换成数字。
console.log(a.getTime() - 10);
console.log(a.getTime() + 10);
My fist example demonstrates the power of Date object but it actually appears to be a time bomb
我的第一个例子展示了日期对象的力量,但它实际上似乎是一个定时炸弹
#3
5
看到JsFiddle演示
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);
}
for your HTML Code:
为你的HTML代码:
<div id="showTime"></div>
#4
4
If you don't care about the time component, you can use .getDate()
and .setDate()
to just set the date part.
如果不关心时间组件,可以使用. getdate()和. setdate()来设置日期部分。
So to set your end date to 2 weeks after your start date, do something like this:
因此,要将你的截止日期设为开始日期后的两周,可以这样做:
function GetEndDate(startDate)
{
var endDate = new Date(startDate.getTime());
endDate.setDate(endDate.getDate()+14);
return endDate;
}
To return the difference (in days) between two dates, do this:
要返回两个日期之间的差异(以天为单位),请执行以下操作:
function GetDateDiff(startDate, endDate)
{
return endDate.getDate() - startDate.getDate();
}
Finally, let's modify the first function so it can take the value returned by 2nd as a parameter:
最后,我们修改第一个函数,使其以2返回的值为参数:
function GetEndDate(startDate, days)
{
var endDate = new Date(startDate.getTime());
endDate.setDate(endDate.getDate() + days);
return endDate;
}
#5
3
Thanks @Vincent Robert, I ended up using your basic example, though it's actually newBegin + oldEnd - oldBegin
. Here's the simplified end solution:
感谢@Vincent Robert,我最终使用了您的基本示例,尽管它实际上是newBegin + oldEnd - oldBegin。下面是简化的最终解决方案:
// 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));
}
#6
2
Depending on your needs, this function will calculate the difference between the 2 days, and return a result in days decimal.
根据您的需要,这个函数将计算这2天之间的差值,并返回一个以days decimal为单位的结果。
// 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));
}
#7
2
If using moment.js, there is a simpler solution, which will give you the difference in days in one single line of code.
如果使用的时刻。js,有一种更简单的解决方案,它将在一行代码中提供不同的天数。
moment(endDate).diff(moment(beginDate), 'days');
Additional details can be found in the moment.js page
现在可以找到更多的细节。js页面
Cheers, Miguel
米盖尔,干杯
#8
1
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);
}
#9
0
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')
}
#10
0
alternative modificitaion extended code..
替代modificitaion扩展代码. .
http://jsfiddle.net/vvGPQ/48/
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);
}
#11
0
<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>
#12
0
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
这段代码填充研究多年的持续时间当你输入开始日期和结束日期(资格雷达波日期)的研究和检查时间不到一年如果有警报消息先记住有三个输入元素txtFromQualifDate和第二txtQualifDate第三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;
}
}
#13
0
If you use Date objects and then use the getTime()
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.
如果您使用Date对象,然后对这两个日期使用getTime()函数,它将给出一个数字值,从1970年1月1日开始,它们各自的时间。你可以得到这些数字之间的差值。
If that doesn't help you out, check out the complete documentation: http://www.w3schools.com/jsref/jsref_obj_date.asp
如果这对您没有帮助,请查看完整的文档:http://www.w3schools.com/jsref/jsref_obj_date.asp
#14
0
Below code will return the days left from today to futures date.
以下代码将返回从今天到期货的剩余天数。
Dependencies: jQuery and MomentJs.
依赖性:jQuery和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');
#15
0
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);
#16
0
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);