For example, given two dates in input boxes:
<input id="first" value="1/1/2000"/>
<input id="second" value="1/1/2001"/>
<script>
alert(datediff("day", first, second)); // what goes here?
</script>
How do I get the number of days between two dates in JavaScript?
Here is a quick and dirty implementation of datediff, as a proof of concept to solve the problem as presented in the question. It relies on the fact that you can get the elapsed milliseconds between two dates by subtracting them, which coerces them into their primitive number value (milliseconds since the start of 1970).
/**
* Take the difference between the dates and divide by milliseconds per day.
* Round to nearest whole number to deal with DST.
*/
function datediff(first, second) {
return Math.round((second - first) / (1000 * 60 * 60 * 24));
}
/**
* new Date("dateString") is browser-dependent and discouraged, so we'll write
* a simple parse function for U.S. date format (which does no error checking)
*/
function parseDate(str) {
var mdy = str.split('/');
return new Date(mdy[2], mdy[0] - 1, mdy[1]);
}
alert(datediff(parseDate(first.value), parseDate(second.value)));
<input id="first" value="1/1/2000"/>
<input id="second" value="1/1/2001"/>
You should be aware that the "normal" Date APIs (without "UTC" in the name) operate in the local timezone of the user's browser, so in general you could run into issues if your user is in a timezone that you don't expect, and your code will have to deal with Daylight Saving Time transitions. You should carefully read the documentation for the Date object and its methods, and for anything more complicated, strongly consider using a library that offers more safe and powerful APIs for date manipulation.
Numbers and Dates -- MDN JavaScript Guide
Date -- MDN JavaScript reference
Also, for illustration purposes, the snippet uses named access on the window object for brevity, but in production you should use standardized APIs like getElementById, or more likely, some UI framework.
As of this writing, only one of the other answers correctly handles DST (daylight saving time) transitions. Here are the results on a system located in California:
1/1/2013- 3/10/2013- 11/3/2013-
User Formula 2/1/2013 3/11/2013 11/4/2013 Result
--------- --------------------------- -------- --------- --------- ---------
Miles (d2 - d1) / N 31 0.9583333 1.0416666 Incorrect
some Math.floor((d2 - d1) / N) 31 0 1 Incorrect
fuentesjr Math.round((d2 - d1) / N) 31 1 1 Correct
toloco Math.ceiling((d2 - d1) / N) 31 1 2 Incorrect
N = 86400000
Although Math.round returns the correct results, I think it's somewhat clunky. Instead, by explicitly accounting for changes to the UTC offset when DST begins or ends, we can use exact arithmetic:
function treatAsUTC(date) {
var result = new Date(date);
result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
return result;
}
function daysBetween(startDate, endDate) {
var millisecondsPerDay = 24 * 60 * 60 * 1000;
return (treatAsUTC(endDate) - treatAsUTC(startDate)) / millisecondsPerDay;
}
alert(daysBetween($('#first').val(), $('#second').val()));
Explanation
JavaScript date calculations are tricky because Date objects store times internally in UTC, not local time. For example, 3/10/2013 12:00 AM Pacific Standard Time (UTC-08:00) is stored as 3/10/2013 8:00 AM UTC, and 3/11/2013 12:00 AM Pacific Daylight Time (UTC-07:00) is stored as 3/11/2013 7:00 AM UTC. On this day, midnight to midnight local time is only 23 hours in UTC!
Although a day in local time can have more or less than 24 hours, a day in UTC is always exactly 24 hours.1 The daysBetween method shown above takes advantage of this fact by first calling treatAsUTC to adjust both local times to midnight UTC, before subtracting and dividing.
1. JavaScript ignores leap seconds.
The easiest way to get the difference between two dates:
var diff = Math.floor((Date.parse(str2) - Date.parse(str1)) / 86400000);
You get the difference days (or NaN if one or both could not be parsed). The parse date gived the result in milliseconds and to get it by day you have to divided it by 24 * 60 * 60 * 1000
If you want it divided by days, hours, minutes, seconds and milliseconds:
function dateDiff( str1, str2 ) {
var diff = Date.parse( str2 ) - Date.parse( str1 );
return isNaN( diff ) ? NaN : {
diff : diff,
ms : Math.floor( diff % 1000 ),
s : Math.floor( diff / 1000 % 60 ),
m : Math.floor( diff / 60000 % 60 ),
h : Math.floor( diff / 3600000 % 24 ),
d : Math.floor( diff / 86400000 )
};
}
Here is my refactored version of James version:
function mydiff(date1,date2,interval) {
var second=1000, minute=second*60, hour=minute*60, day=hour*24, week=day*7;
date1 = new Date(date1);
date2 = new Date(date2);
var timediff = date2 - date1;
if (isNaN(timediff)) return NaN;
switch (interval) {
case "years": return date2.getFullYear() - date1.getFullYear();
case "months": return (
( date2.getFullYear() * 12 + date2.getMonth() )
-
( date1.getFullYear() * 12 + date1.getMonth() )
);
case "weeks" : return Math.floor(timediff / week);
case "days" : return Math.floor(timediff / day);
case "hours" : return Math.floor(timediff / hour);
case "minutes": return Math.floor(timediff / minute);
case "seconds": return Math.floor(timediff / second);
default: return undefined;
}
}
I recommend using the moment.js library (http://momentjs.com/docs/#/displaying/difference/). It handles daylight savings time correctly and in general is great to work with.
Example:
var start = moment("2013-11-03");
var end = moment("2013-11-04");
end.diff(start, "days")
1
The following solutions will assume these variables are available in the code:
const startDate = '2020-01-01';
const endDate = '2020-03-15';
Native JS
Steps:
Set start date
Set end date
Calculate difference
Convert milliseconds to days
const diffInMs = new Date(endDate) - new Date(startDate)
const diffInDays = diffInMs / (1000 * 60 * 60 * 24);
Comment:
I know this is not part of your questions but in general, I would not recommend doing any date calculation or manipulation in vanilla JavaScript and rather use a library like date-fns, Luxon or moment.js for it due to many edge cases.
This vanilla JavaScript answer calculates the days as a decimal number. Also, it could run into edge cases when working with Daylight Savings Time
Using a Library
- Date-fns
const differenceInDays = require('date-fns/differenceInDays');
const diffInDays = differenceInDays(new Date(endDate), new Date(startDate));
documentation: https://date-fns.org/v2.16.1/docs/differenceInDays
- Luxon
const { DateTime } = require('luxon');
const diffInDays = DateTime.fromISO(endDate).diff(DateTime.fromISO(startDate), 'days').toObject().days;
documentation: https://moment.github.io/luxon/docs/class/src/datetime.js~DateTime.html#instance-method-diff
- Moment.js
const moment = require('moment');
const diffInDays = moment(endDate).diff(moment(startDate), 'days');
documentation: https://momentjs.com/docs/#/displaying/difference/
Examples on RunKit
I would go ahead and grab this small utility and in it you will find functions to this for you. Here's a short example:
<script type="text/javascript" src="date.js"></script>
<script type="text/javascript">
var minutes = 1000*60;
var hours = minutes*60;
var days = hours*24;
var foo_date1 = getDateFromFormat("02/10/2009", "M/d/y");
var foo_date2 = getDateFromFormat("02/12/2009", "M/d/y");
var diff_date = Math.round((foo_date2 - foo_date1)/days);
alert("Diff date is: " + diff_date );
</script>
Using Moment.js
var future = moment('05/02/2015');
var start = moment('04/23/2015');
var d = future.diff(start, 'days'); // 9
console.log(d);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment-with-locales.min.js"></script>
Try This
let today = new Date().toISOString().slice(0, 10)
const startDate = '2021-04-15';
const endDate = today;
const diffInMs = new Date(endDate) - new Date(startDate)
const diffInDays = diffInMs / (1000 * 60 * 60 * 24);
alert( diffInDays );
To Calculate days between 2 given dates you can use the following code.Dates I use here are Jan 01 2016 and Dec 31 2016
var day_start = new Date("Jan 01 2016");
var day_end = new Date("Dec 31 2016");
var total_days = (day_end - day_start) / (1000 * 60 * 60 * 24);
document.getElementById("demo").innerHTML = Math.round(total_days);
<h3>DAYS BETWEEN GIVEN DATES</h3>
<p id="demo"></p>
Date values in JS are datetime values.
So, direct date computations are inconsistent:
(2013-11-05 00:00:00) - (2013-11-04 10:10:10) < 1 day
for example we need to convert de 2nd date:
(2013-11-05 00:00:00) - (2013-11-04 00:00:00) = 1 day
the method could be truncate the mills in both dates:
var date1 = new Date('2013/11/04 00:00:00');
var date2 = new Date('2013/11/04 10:10:10'); //less than 1
var start = Math.floor(date1.getTime() / (3600 * 24 * 1000)); //days as integer from..
var end = Math.floor(date2.getTime() / (3600 * 24 * 1000)); //days as integer from..
var daysDiff = end - start; // exact dates
console.log(daysDiff);
date2 = new Date('2013/11/05 00:00:00'); //1
var start = Math.floor(date1.getTime() / (3600 * 24 * 1000)); //days as integer from..
var end = Math.floor(date2.getTime() / (3600 * 24 * 1000)); //days as integer from..
var daysDiff = end - start; // exact dates
console.log(daysDiff);
Better to get rid of DST, Math.ceil, Math.floor etc. by using UTC times:
var firstDate = Date.UTC(2015,01,2);
var secondDate = Date.UTC(2015,04,22);
var diff = Math.abs((firstDate.valueOf()
- secondDate.valueOf())/(24*60*60*1000));
This example gives difference 109 days. 24*60*60*1000 is one day in milliseconds.
It is possible to calculate a full proof days difference between two dates resting across different TZs using the following formula:
var start = new Date('10/3/2015');
var end = new Date('11/2/2015');
var days = (end - start) / 1000 / 60 / 60 / 24;
console.log(days);
// actually its 30 ; but due to daylight savings will show 31.0xxx
// which you need to offset as below
days = days - (end.getTimezoneOffset() - start.getTimezoneOffset()) / (60 * 24);
console.log(days);
I found this question when I want do some calculate on two date, but the date have hours and minutes value, I modified #michael-liu 's answer to fit my requirement, and it passed my test.
diff days 2012-12-31 23:00 and 2013-01-01 01:00 should equal 1. (2 hour)
diff days 2012-12-31 01:00 and 2013-01-01 23:00 should equal 1. (46 hour)
function treatAsUTC(date) {
var result = new Date(date);
result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
return result;
}
var millisecondsPerDay = 24 * 60 * 60 * 1000;
function diffDays(startDate, endDate) {
return Math.floor(treatAsUTC(endDate) / millisecondsPerDay) - Math.floor(treatAsUTC(startDate) / millisecondsPerDay);
}
This may not be the most elegant solution, but it seems to answer the question with a relatively simple bit of code, I think. Can't you use something like this:
function dayDiff(startdate, enddate) {
var dayCount = 0;
while(enddate >= startdate) {
dayCount++;
startdate.setDate(startdate.getDate() + 1);
}
return dayCount;
}
This is assuming you are passing date objects as parameters.
var start= $("#firstDate").datepicker("getDate");
var end= $("#SecondDate").datepicker("getDate");
var days = (end- start) / (1000 * 60 * 60 * 24);
alert(Math.round(days));
jsfiddle example :)
One-Liner and small
const diff=(e,t)=>Math.floor((new Date(e).getTime()-new Date(t).getTime())/1000*60*60*24);
// or
const diff=(e,t)=>Math.floor((new Date(e)-new Date(t))/864e5);
// or
const diff=(a,b)=>(new Date(a)-new Date(b))/864e5|0;
// use
diff('1/1/2001', '1/1/2000')
For TypeScript
const diff = (from: string, to: string) => Math.floor((new Date(from).getTime() - new Date(to).getTime()) / 86400000);
I think the solutions aren't correct 100% I would use ceil instead of floor, round will work but it isn't the right operation.
function dateDiff(str1, str2){
var diff = Date.parse(str2) - Date.parse(str1);
return isNaN(diff) ? NaN : {
diff: diff,
ms: Math.ceil(diff % 1000),
s: Math.ceil(diff / 1000 % 60),
m: Math.ceil(diff / 60000 % 60),
h: Math.ceil(diff / 3600000 % 24),
d: Math.ceil(diff / 86400000)
};
}
What about using formatDate from DatePicker widget? You could use it to convert the dates in timestamp format (milliseconds since 01/01/1970) and then do a simple subtraction.
function timeDifference(date1, date2) {
var oneDay = 24 * 60 * 60; // hours*minutes*seconds
var oneHour = 60 * 60; // minutes*seconds
var oneMinute = 60; // 60 seconds
var firstDate = date1.getTime(); // convert to milliseconds
var secondDate = date2.getTime(); // convert to milliseconds
var seconds = Math.round(Math.abs(firstDate - secondDate) / 1000); //calculate the diffrence in seconds
// the difference object
var difference = {
"days": 0,
"hours": 0,
"minutes": 0,
"seconds": 0,
}
//calculate all the days and substract it from the total
while (seconds >= oneDay) {
difference.days++;
seconds -= oneDay;
}
//calculate all the remaining hours then substract it from the total
while (seconds >= oneHour) {
difference.hours++;
seconds -= oneHour;
}
//calculate all the remaining minutes then substract it from the total
while (seconds >= oneMinute) {
difference.minutes++;
seconds -= oneMinute;
}
//the remaining seconds :
difference.seconds = seconds;
//return the difference object
return difference;
}
console.log(timeDifference(new Date(2017,0,1,0,0,0),new Date()));
Date.prototype.days = function(to) {
return Math.abs(Math.floor(to.getTime() / (3600 * 24 * 1000)) - Math.floor(this.getTime() / (3600 * 24 * 1000)))
}
console.log(new Date('2014/05/20').days(new Date('2014/05/23'))); // 3 days
console.log(new Date('2014/05/23').days(new Date('2014/05/20'))); // 3 days
Simple, easy, and sophisticated. This function will be called in every 1 sec to update time.
const year = (new Date().getFullYear());
const bdayDate = new Date("04,11,2019").getTime(); //mmddyyyy
// countdown
let timer = setInterval(function () {
// get today's date
const today = new Date().getTime();
// get the difference
const diff = bdayDate - today;
// math
let days = Math.floor(diff / (1000 * 60 * 60 * 24));
let hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
let minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
let seconds = Math.floor((diff % (1000 * 60)) / 1000);
}, 1000);
I had the same issue in Angular. I do the copy because else he will overwrite the first date. Both dates must have time 00:00:00 (obviously)
/*
* Deze functie gebruiken we om het aantal dagen te bereken van een booking.
* */
$scope.berekenDagen = function ()
{
$scope.booking.aantalDagen=0;
/*De loper is gelijk aan de startdag van je reservatie.
* De copy is nodig anders overschijft angular de booking.van.
* */
var loper = angular.copy($scope.booking.van);
/*Zolang de reservatie beschikbaar is, doorloop de weekdagen van je start tot einddatum.*/
while (loper < $scope.booking.tot) {
/*Tel een dag op bij je loper.*/
loper.setDate(loper.getDate() + 1);
$scope.booking.aantalDagen++;
}
/*Start datum telt natuurlijk ook mee*/
$scope.booking.aantalDagen++;
$scope.infomsg +=" aantal dagen: "+$scope.booking.aantalDagen;
};
If you have two unix timestamps, you can use this function (made a little more verbose for the sake of clarity):
// Calculate number of days between two unix timestamps
// ------------------------------------------------------------
var daysBetween = function(timeStampA, timeStampB) {
var oneDay = 24 * 60 * 60 * 1000; // hours * minutes * seconds * milliseconds
var firstDate = new Date(timeStampA * 1000);
var secondDate = new Date(timeStampB * 1000);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
return diffDays;
};
Example:
daysBetween(1096580303, 1308713220); // 2455
Be careful when using milliseconds.
The date.getTime() returns milliseconds and doing math operation with milliseconds requires to include
Daylight Saving Time (DST)
checking if both dates have the same time (hours, minutes, seconds, milliseconds)
make sure what behavior of days diff is required: 19 September 2016 - 29 September 2016 = 1 or 2 days difference?
The example from comment above is the best solution I found so far
https://stackoverflow.com/a/11252167/2091095 . But use +1 to its result if you want the to count all days involved.
function treatAsUTC(date) {
var result = new Date(date);
result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
return result;
}
function daysBetween(startDate, endDate) {
var millisecondsPerDay = 24 * 60 * 60 * 1000;
return (treatAsUTC(endDate) - treatAsUTC(startDate)) / millisecondsPerDay;
}
var diff = daysBetween($('#first').val(), $('#second').val()) + 1;
I used below code to experiment the posting date functionality for a news post.I calculate the minute or hour or day or year based on the posting date and current date.
var startDate= new Date("Mon Jan 01 2007 11:00:00");
var endDate =new Date("Tue Jan 02 2007 12:50:00");
var timeStart = startDate.getTime();
var timeEnd = endDate.getTime();
var yearStart = startDate.getFullYear();
var yearEnd = endDate.getFullYear();
if(yearStart == yearEnd)
{
var hourDiff = timeEnd - timeStart;
var secDiff = hourDiff / 1000;
var minDiff = hourDiff / 60 / 1000;
var hDiff = hourDiff / 3600 / 1000;
var myObj = {};
myObj.hours = Math.floor(hDiff);
myObj.minutes = minDiff
if(myObj.hours >= 24)
{
console.log(Math.floor(myObj.hours/24) + "day(s) ago")
}
else if(myObj.hours>0)
{
console.log(myObj.hours +"hour(s) ago")
}
else
{
console.log(Math.abs(myObj.minutes) +"minute(s) ago")
}
}
else
{
var yearDiff = yearEnd - yearStart;
console.log( yearDiff +" year(s) ago");
}
if you wanna have an DateArray with dates try this:
<script>
function getDates(startDate, stopDate) {
var dateArray = new Array();
var currentDate = moment(startDate);
dateArray.push( moment(currentDate).format('L'));
var stopDate = moment(stopDate);
while (dateArray[dateArray.length -1] != stopDate._i) {
dateArray.push( moment(currentDate).format('L'));
currentDate = moment(currentDate).add(1, 'days');
}
return dateArray;
}
</script>
DebugSnippet
The simple way to calculate days between two dates is to remove both of their time component i.e. setting hours, minutes, seconds and milliseconds to 0 and then subtracting their time and diving it with milliseconds worth of one day.
var firstDate= new Date(firstDate.setHours(0,0,0,0));
var secondDate= new Date(secondDate.setHours(0,0,0,0));
var timeDiff = firstDate.getTime() - secondDate.getTime();
var diffDays =timeDiff / (1000 * 3600 * 24);
function formatDate(seconds, dictionary) {
var foo = new Date;
var unixtime_ms = foo.getTime();
var unixtime = parseInt(unixtime_ms / 1000);
var diff = unixtime - seconds;
var display_date;
if (diff <= 0) {
display_date = dictionary.now;
} else if (diff < 60) {
if (diff == 1) {
display_date = diff + ' ' + dictionary.second;
} else {
display_date = diff + ' ' + dictionary.seconds;
}
} else if (diff < 3540) {
diff = Math.round(diff / 60);
if (diff == 1) {
display_date = diff + ' ' + dictionary.minute;
} else {
display_date = diff + ' ' + dictionary.minutes;
}
} else if (diff < 82800) {
diff = Math.round(diff / 3600);
if (diff == 1) {
display_date = diff + ' ' + dictionary.hour;
} else {
display_date = diff + ' ' + dictionary.hours;
}
} else {
diff = Math.round(diff / 86400);
if (diff == 1) {
display_date = diff + ' ' + dictionary.day;
} else {
display_date = diff + ' ' + dictionary.days;
}
}
return display_date;
}
I recently had the same question, and coming from a Java world, I immediately started to search for a JSR 310 implementation for JavaScript. JSR 310 is a Date and Time API for Java (standard shipped as of Java 8). I think the API is very well designed.
Fortunately, there is a direct port to Javascript, called js-joda.
First, include js-joda in the <head>:
<script
src="https://cdnjs.cloudflare.com/ajax/libs/js-joda/1.11.0/js-joda.min.js"
integrity="sha512-piLlO+P2f15QHjUv0DEXBd4HvkL03Orhi30Ur5n1E4Gk2LE4BxiBAP/AD+dxhxpW66DiMY2wZqQWHAuS53RFDg=="
crossorigin="anonymous"></script>
Then simply do this:
let date1 = JSJoda.LocalDate.of(2020, 12, 1);
let date2 = JSJoda.LocalDate.of(2021, 1, 1);
let daysBetween = JSJoda.ChronoUnit.DAYS.between(date1, date2);
Now daysBetween contains the number of days between. Note that the end date is exclusive.
// JavaScript / NodeJs answer
let startDate = new Date("2022-09-19");
let endDate = new Date("2022-09-26");
let difference = startDate.getTime() - endDate.getTime();
console.log(difference);
let TotalDiffDays = Math.ceil(difference / (1000 * 3600 * 24));
console.log(TotalDiffDays + " days :) ");
Related
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.
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)
JavaScript perfectly supports date difference out of the box
https://jsfiddle.net/b9chris/v5twbe3h/
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'); // 364
console.log(Math.floor(((b - a) % msDay) / msMinute) + ' full minutes between'); // 0
Now some pitfalls. Try this:
console.log(a - 10); // 1331614798990
console.log(a + 10); // mixed string
So if you have risk of adding a number and Date, convert Date to number directly.
console.log(a.getTime() - 10); // 1331614798990
console.log(a.getTime() + 10); // 1331614799010
My fist example demonstrates the power of Date object but it actually appears to be a time bomb
See JsFiddle DEMO
var date1 = new Date();
var date2 = new Date("2025/07/30 21:59:00");
//Customise date2 for your required future time
showDiff();
function showDiff(date1, date2){
var diff = (date2 - date1)/1000;
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:
<div id="showTime"></div>
If you don't care about the time component, you can use .getDate() and .setDate() to just set the date part.
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:
function GetEndDate(startDate, days)
{
var endDate = new Date(startDate.getTime());
endDate.setDate(endDate.getDate() + days);
return endDate;
}
Thanks #Vincent Robert, I ended up using your basic example, though it's actually newBegin + oldEnd - oldBegin. Here's the simplified end solution:
// 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));
}
Depending on your needs, this function will calculate the difference between the 2 days, and return a result in 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));
}
If using moment.js, there is a simpler solution, which will give you the difference in days in one single line of code.
moment(endDate).diff(moment(beginDate), 'days');
Additional details can be found in the moment.js page
Cheers,
Miguel
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);
}
alternative modificitaion extended code..
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);
}
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');
<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>
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;
}
}
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.
If that doesn't help you out, check out the complete documentation: http://www.w3schools.com/jsref/jsref_obj_date.asp
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);
To get the date difference in milliseconds between two dates:
var diff = Math.abs(date1 - date2);
I'm not sure what you mean by converting the difference back into a date though.
Many answers here are based on a direct subtraction of Date objects like new Date(…) - new Date(…). This is syntactically wrong. Browsers still accept it because of backward compatibility. But modern JS linters will throw at you.
The right way to calculate date differences in milliseconds is new Date(…).getTime() - new Date(…).getTime():
// Time difference between two dates
let diffInMillis = new Date(…).getTime() - new Date(…).getTime()
If you want to calculate the time difference to now, you can just remove the argument from the first Date:
// Time difference between now and some date
let diffInMillis = new Date().getTime() - new Date(…).getTime()
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')
}
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);
I have start date time and end time,i need to split how many days , hours ,minutes in the two dates
for example ,
startdatetime = "09-06-2017 10:30"
enddatetime = "10-06-2017 11:45"
i need this result : 1 day 1 hour and 15 minutes
I try this one
var t = end - start;
var z = parseInt(t / 1000 / 60);
var time = display(z);
function display(a)
{
console.log(a);
var hours = Math.trunc(a/60);
var minutes = a % 60;
var one_day=1000*60*60*24
var days = Math.ceil(a/one_day)
var time = [hours,minutes,days];
return time;
}
i get the following 1day 24 hours and 15 minutes , can anyone help me , if its new logic means i will change into it,thanks in advance
Using momentjs, you can :
Parse your input string using moment(String, String)
Parse your input string using moment.utc
Get difference using diff() function
Create a duration from the difference value
Use duration days(), hours(), minutes() to get your result
Here a live sample:
var startdatetime = "2017-06-09T07:00:01.000Z";
var enddatetime = "2017-06-10T09:00:00.000Z";
// Parse input
var mStart = moment.utc(startdatetime);
var mEnd = moment.utc(enddatetime);
// Calculate difference and create duration
var dur = moment.duration( mEnd.diff(mStart) );
// Show the result
console.log(dur.days() + ' days ' + dur.hours() + ' hour ' + dur.minutes() + ' minutes');
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
If you want you can use moment-duration-format plug-in to get the same result using format() method on duration. Here a working sample:
var startdatetime = "2017-06-09T07:00:01.000Z";
var enddatetime = "2017-06-10T09:00:00.000Z";
// Parse input
var mStart = moment.utc(startdatetime);
var mEnd = moment.utc(enddatetime);
// Calculate difference and create duration
var dur = moment.duration( mEnd.diff(mStart) );
// Show the result
console.log(dur.format('d [day] h [hour] m [minutes]'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>
Well, if you look at documentation for javascript Date objects, there is a getTime() method . You can also use the valueOf() method. They both return the number of milliseconds representing your Date object.
You can simply call that on both Date objects and then find the difference. Once you have the difference you can find the amount of secs, mins , hrs, days, etc. Here is an example:
var start = new Date(*some date*);
var end = new Date(*some date*);
var dif = end.valueOf() - start.valueOf();
if (dif >= 0) {
var secs = Math.floor(dif / 1000 % 60);
var mins = Math.floor(dif / 1000 / 60 % 60);
var hrs = Math.floor(dif / 1000 / 60 / 60 % 24);
var days =
Math.floor(dif / 1000 / 60 / 60 / 24 % 365);
var yrs =
Math.floor(dif / 1000 / 60 / 60 / 24 / 365);
Try the following:
var t = end - start;
var z = parseInt(t / 1000 / 60);
var time = display(z);
function display(minutes)
{
var hours = (minutes / 60 | 0) % 24;
var minutes = (minutes | 0) % 60;
var days = minutes / 60 / 24 | 0;
return [hours, minutes, days];
}
Note that in javascript, doing x | 0 is the same as Math.floor(x).
It looks to me like your calculation for hours still has the days in it. Once you have established the days, just subtract those out when you calculate the hours.
var start = new Date("June 09, 2017 10:30:00");
var end = new Date("June 10, 2017 11:45:00");
var t = end - start;
var z = parseInt(t / 1000 / 60);
var time = display(z);
console.log(time);
function display(a)
{
var minutes = a % 60;
var one_day=1000*60*60*24
var days = Math.ceil(a/one_day)
var hours = Math.trunc((a-(days*1440))/60);
var time = [hours,minutes,days];
return time;
}
Having said that, I highly recommend moment.js to handle this type of thing, if you can.
var startDateTime = 1497029400000;
var endDateTime = 1497120300000;
var timeDifference = endDateTime - startDateTime
// with the given dates, days equals 1.0520833333333333
// we want to extract the trailing decimal values using modulus to get the other times
function getTimeDifference(timeDifference) {
var days = timeDifference/1000/60/60/24
days >= 1
? var dayCount = Math.trunc(days); // store the day count
: var dayCount = 0; // it is less than one day
// get the remaining hours
var hours = (days % 1) * 24;
var hoursCount = Math.trunc((days % 1) * 24);
// get the remaining minutes
var minutesCount = Math.ceil((hours % 1) * 60);
}
I need to be able to round time to the next nearest 5 minutes.
Time now 11:54 - clock is 11:55
Time now 11:56 - clock is 12:00
It can never round down just always up to the next time.
I am using this code at the moment but this will round down as well
var time = 1000 * 60 * 5;
var date = new Date();
var rounded = new Date(Math.round(date.getTime() / time) * time);
Add 2.5 minutes to your time, then round.
11:54 + 2.5 = 11:56:30 -> 11:55
11:56 + 2.5 = 11:58:30 -> 12:00
You could divide out 5, do a Math.ceil then multiply back up by 5
minutes = (5 * Math.ceil(minutes / 5));
I had the same problem, but I needed to round down, and I changed your code to this:
var time = 1000 * 60 * 5;
var date = new Date();
var rounded = new Date(date.getTime() - (date.getTime() % time));
I think that to round up It wiil be something like this:
var time = 1000 * 60 * 5;
var date = new Date();
var rounded = new Date(date.getTime() + time - (date.getTime() % time));
Pass any cycle you want in milliseconds to get next cycle example 5,10,15,30,60 minutes
function calculateNextCycle(interval) {
const timeStampCurrentOrOldDate = Date.now();
const timeStampStartOfDay = new Date().setHours(0, 0, 0, 0);
const timeDiff = timeStampCurrentOrOldDate - timeStampStartOfDay;
const mod = Math.ceil(timeDiff / interval);
return new Date(timeStampStartOfDay + (mod * interval));
}
console.log(calculateNextCycle(5 * 60 * 1000)); // pass in milliseconds
var b = Date.now() + 15E4,
c = b % 3E5;
rounded = new Date(15E4>=c?b-c:b+3E5-c);
With ES6 and partial functions it can be elegant:
const roundDownTo = roundTo => x => Math.floor(x / roundTo) * roundTo;
const roundUpTo = roundTo => x => Math.ceil(x / roundTo) * roundTo;
const roundUpTo5Minutes = roundUpTo(1000 * 60 * 5);
const ms = roundUpTo5Minutes(new Date())
console.log(new Date(ms)); // Wed Jun 05 2019 15:55:00 GMT+0200
If I have two dates, how can I use JavaScript to get the difference between the two dates in minutes?
You may checkout this code:
var today = new Date();
var Christmas = new Date(today.getFullYear() + "-12-25");
var diffMs = (Christmas - today); // milliseconds between now & Christmas
var diffDays = Math.floor(diffMs / 86400000); // days
var diffHrs = Math.floor((diffMs % 86400000) / 3600000); // hours
var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes
console.log(diffDays + " days, " + diffHrs + " hours, " + diffMins + " minutes until Christmas =)");
or var diffMins = Math.floor((... to discard seconds if you don't want to round minutes.
Subtracting two Date objects gives you the difference in milliseconds, e.g.:
var diff = Math.abs(new Date('2011/10/09 12:00') - new Date('2011/10/09 00:00'));
Math.abs is used to be able to use the absolute difference (so new Date('2011/10/09 00:00') - new Date('2011/10/09 12:00') gives the same result).
Dividing the result by 1000 gives you the number of seconds. Dividing that by 60 gives you the number of minutes. To round to whole minutes, use Math.floor or Math.ceil:
var minutes = Math.floor((diff/1000)/60);
In this example the result will be 720.
[edit 2022] Added a more complete demo snippet, using the aforementioned knowledge.
See also
untilXMas();
function difference2Parts(milliseconds) {
const secs = Math.floor(Math.abs(milliseconds) / 1000);
const mins = Math.floor(secs / 60);
const hours = Math.floor(mins / 60);
const days = Math.floor(hours / 24);
const millisecs = Math.floor(Math.abs(milliseconds)) % 1000;
const multiple = (term, n) => n !== 1 ? `${n} ${term}s` : `1 ${term}`;
return {
days: days,
hours: hours % 24,
hoursTotal: hours,
minutesTotal: mins,
minutes: mins % 60,
seconds: secs % 60,
secondsTotal: secs,
milliSeconds: millisecs,
get diffStr() {
return `${multiple(`day`, this.days)}, ${
multiple(`hour`, this.hours)}, ${
multiple(`minute`, this.minutes)} and ${
multiple(`second`, this.seconds)}`;
},
get diffStrMs() {
return `${this.diffStr.replace(` and`, `, `)} and ${
multiple(`millisecond`, this.milliSeconds)}`;
},
};
}
function untilXMas() {
const nextChristmas = new Date(Date.UTC(new Date().getFullYear(), 11, 25));
const report = document.querySelector(`#nextXMas`);
const diff = () => {
const diffs = difference2Parts(nextChristmas - new Date());
report.innerHTML = `Awaiting next XMas 🙂 (${
diffs.diffStrMs.replace(/(\d+)/g, a => `<b>${a}</b>`)})<br>
<br>In other words, until next XMas lasts…<br>
In minutes: <b>${diffs.minutesTotal}</b><br>In hours: <b>${
diffs.hoursTotal}</b><br>In seconds: <b>${diffs.secondsTotal}</b>`;
setTimeout(diff, 200);
};
return diff();
}
body {
font: 14px/17px normal verdana, arial;
margin: 1rem;
}
<div id="nextXMas"></div>
var startTime = new Date('2012/10/09 12:00');
var endTime = new Date('2013/10/09 12:00');
var difference = endTime.getTime() - startTime.getTime(); // This will give difference in milliseconds
var resultInMinutes = Math.round(difference / 60000);
A simple function to perform this calculation:
function getMinutesBetweenDates(startDate, endDate) {
var diff = endDate.getTime() - startDate.getTime();
return (diff / 60000);
}
That's should show the difference between the two dates in minutes. Try it in your browser:
const currDate = new Date('Tue Feb 13 2018 13:04:58 GMT+0200 (EET)')
const oldDate = new Date('Tue Feb 13 2018 12:00:58 GMT+0200 (EET)')
(currDate - oldDate) / 60000 // 64
This problem is solved easily with moment.js, like this example:
var difference = mostDate.diff(minorDate, "minutes");
The second parameter can be changed for another parameters, see the moment.js documentation.
e.g.: "days", "hours", "minutes", etc.
http://momentjs.com/docs/
The CDN for moment.js is available here:
https://cdnjs.com/libraries/moment.js
Thanks.
EDIT:
mostDate and minorDate should be a moment type.
EDIT 2:
For those who are reading my answer in 2020+, momentjs is now a legacy project.
If you are still looking for a well-known library to do this job, I would recommend date-fns.
// How many minutes are between 2 July 2014 12:07:59 and 2 July 2014 12:20:00?
var result = differenceInMinutes(
new Date(2014, 6, 2, 12, 20, 0),
new Date(2014, 6, 2, 12, 7, 59)
)
//=> 12
You can do as follows:
Get difference of dates(Difference will be in milliseconds)
Convert milliseconds into minutes i-e ms/1000/60
The Code:
let dateOne = new Date("2020-07-10");
let dateTwo = new Date("2020-07-11");
let msDifference = dateTwo - dateOne;
let minutes = Math.floor(msDifference/1000/60);
console.log("Minutes between two dates =",minutes);
For those that like to work with small numbers
const today = new Date();
const endDate = new Date(startDate.setDate(startDate.getDate() + 7));
const days = parseInt((endDate - today) / (1000 * 60 * 60 * 24));
const hours = parseInt(Math.abs(endDate - today) / (1000 * 60 * 60) % 24);
const minutes = parseInt(Math.abs(endDate.getTime() - today.getTime()) / (1000 * 60) % 60);
const seconds = parseInt(Math.abs(endDate.getTime() - today.getTime()) / (1000) % 60);
Here's some fun I had solving something similar in node.
function formatTimeDiff(date1, date2) {
return Array(3)
.fill([3600, date1.getTime() - date2.getTime()])
.map((v, i, a) => {
a[i+1] = [a[i][0]/60, ((v[1] / (v[0] * 1000)) % 1) * (v[0] * 1000)];
return `0${Math.floor(v[1] / (v[0] * 1000))}`.slice(-2);
}).join(':');
}
const millis = 1000;
const utcEnd = new Date(1541424202 * millis);
const utcStart = new Date(1541389579 * millis);
const utcDiff = formatTimeDiff(utcEnd, utcStart);
console.log(`Dates:
Start : ${utcStart}
Stop : ${utcEnd}
Elapsed : ${utcDiff}
`);
/*
Outputs:
Dates:
Start : Mon Nov 05 2018 03:46:19 GMT+0000 (UTC)
Stop : Mon Nov 05 2018 13:23:22 GMT+0000 (UTC)
Elapsed : 09:37:02
*/
You can see it in action at https://repl.it/#GioCirque/TimeSpan-Formatting
The following code worked for me,
function timeDiffCalc(dateNow,dateFuture) {
var newYear1 = new Date(dateNow);
var newYear2 = new Date(dateFuture);
var dif = (newYear2 - newYear1);
var dif = Math.round((dif/1000)/60);
console.log(dif);
}
It works easily:
var endTime = $("#ExamEndTime").val();
var startTime = $("#ExamStartTime").val();
//create date format
var timeStart = new Date("01/01/2007 " + startTime);
var timeEnd = new Date("01/01/2007 " + endTime);
var msInMinute = 60 * 1000;
var difference = Math.round(Math.abs(timeEnd - timeStart) / msInMinute);
$("#txtCalculate").val(difference);
this will work
duration = moment.duration(moment(end_time).diff(moment(start_time)))
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.
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)
JavaScript perfectly supports date difference out of the box
https://jsfiddle.net/b9chris/v5twbe3h/
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'); // 364
console.log(Math.floor(((b - a) % msDay) / msMinute) + ' full minutes between'); // 0
Now some pitfalls. Try this:
console.log(a - 10); // 1331614798990
console.log(a + 10); // mixed string
So if you have risk of adding a number and Date, convert Date to number directly.
console.log(a.getTime() - 10); // 1331614798990
console.log(a.getTime() + 10); // 1331614799010
My fist example demonstrates the power of Date object but it actually appears to be a time bomb
See JsFiddle DEMO
var date1 = new Date();
var date2 = new Date("2025/07/30 21:59:00");
//Customise date2 for your required future time
showDiff();
function showDiff(date1, date2){
var diff = (date2 - date1)/1000;
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:
<div id="showTime"></div>
If you don't care about the time component, you can use .getDate() and .setDate() to just set the date part.
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:
function GetEndDate(startDate, days)
{
var endDate = new Date(startDate.getTime());
endDate.setDate(endDate.getDate() + days);
return endDate;
}
Thanks #Vincent Robert, I ended up using your basic example, though it's actually newBegin + oldEnd - oldBegin. Here's the simplified end solution:
// 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));
}
Depending on your needs, this function will calculate the difference between the 2 days, and return a result in 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));
}
If using moment.js, there is a simpler solution, which will give you the difference in days in one single line of code.
moment(endDate).diff(moment(beginDate), 'days');
Additional details can be found in the moment.js page
Cheers,
Miguel
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);
}
alternative modificitaion extended code..
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);
}
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');
<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>
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;
}
}
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.
If that doesn't help you out, check out the complete documentation: http://www.w3schools.com/jsref/jsref_obj_date.asp
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);
To get the date difference in milliseconds between two dates:
var diff = Math.abs(date1 - date2);
I'm not sure what you mean by converting the difference back into a date though.
Many answers here are based on a direct subtraction of Date objects like new Date(…) - new Date(…). This is syntactically wrong. Browsers still accept it because of backward compatibility. But modern JS linters will throw at you.
The right way to calculate date differences in milliseconds is new Date(…).getTime() - new Date(…).getTime():
// Time difference between two dates
let diffInMillis = new Date(…).getTime() - new Date(…).getTime()
If you want to calculate the time difference to now, you can just remove the argument from the first Date:
// Time difference between now and some date
let diffInMillis = new Date().getTime() - new Date(…).getTime()
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')
}
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);