Datepicker set by day of year - javascript

This is a followup to a previous question about Datepicker. Trying to show only every third day on the calendar. figured out how to get DOY as integer and use in calendar, however it fails every March - also not able to span two years?
On a second part, if I need to disable a certain day of the week, how do I combine that with current 3rd day feature.
here is JSFiddle DatePicker
function noWeekEnds(date) {
var dow = date.getDay();
if(dow>5 || dow<1) return [false,''];
return [true,''];
}
function unavailable(date) {
var now = date;
var start = new Date(now.getFullYear(), 0, 0);
var diff = now - start;
var oneDay = 1000 * 60 * 60 * 24;
var day = Math.floor(diff / oneDay);
var shift = (day%3===0);
return [shift, "red2", "available"];
return noWeekEnds(date);
/*
need this to span across 2 years i.e.: Jan 8 2015 thru Jan 12/2016
also it fails the 3rd week of every March ???
*/
}
$(document).ready(function() {
$("#datepicker").datepicker({
beforeShowDay: unavailable
});
$('#datepicker').attr('readonly',true);
});

Fixed unavailable function:
http://jsfiddle.net/nbL98a2r/13/
function unavailable(date) {
var start = new Date(2015,0,8);
var end = new Date(2016,0,12);
var now = date;
if(now < start || now > end) return [false, "red2", "available"]
var timeDiff = Math.abs(now.getTime() - start.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
var nwe = noWeekEnds(date);
var shift = (diffDays%3===0) && nwe[0];
return [shift, "red2", "available"]
}

Related

How to calculate the total days between two selected calendar dates

Let say i have startDate = 7/16/2015 and endDate = 7/20/2015. This 2 dates are stored in a SharePoint list.
If user select the exact date with the date in SharePoint list, it can calculate the total days = 2 , which means that without calculate on the other days.
Anyone can please help on this?
I use the following code to calculate the total day of difference without counting on weekend. But I cant figure out the way how to calculate the total day of selected date without counting on other days.
function workingDaysBetweenDates(startDate,endDate) {
// Validate input
if (endDate < startDate)
return 'Invalid !';
// Calculate days between dates
var millisecondsPerDay = 86400 * 1000; // Day in milliseconds
startDate.setHours(0,0,0,1); // Start just after midnight
endDate.setHours(23,59,59,999); // End just before midnight
var diff = endDate - startDate; // Milliseconds between datetime objects
var days = Math.ceil(diff / millisecondsPerDay);
// Subtract two weekend days for every week in between
var weeks = Math.floor(days / 7);
var days = days - (weeks * 2);
// Handle special cases
var startDay = startDate.getDay();
var endDay = endDate.getDay();
// Remove weekend not previously removed.
if (startDay - endDay > 1)
days = days - 2;
// Remove start day if span starts on Sunday but ends before Saturday
if (startDay == 0 && endDay != 6)
days = days - 1;
// Remove end day if span ends on Saturday but starts after Sunday
if (endDay == 6 && startDay != 0)
days = days - 1;
return days;
}
The following function calculates the number of business days between two dates
function getBusinessDatesCount(startDate, endDate) {
var count = 0;
var curDate = startDate;
while (curDate <= endDate) {
var dayOfWeek = curDate.getDay();
if(!((dayOfWeek == 6) || (dayOfWeek == 0)))
count++;
curDate.setDate(curDate.getDate() + 1);
}
return count;
}
//Usage
var startDate = new Date('7/16/2015');
var endDate = new Date('7/20/2015');
var numOfDates = getBusinessDatesCount(startDate,endDate);
$('div#result').text(numOfDates);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"/>
First you have to calculate the difference in time, then convert the time to days
var calculateDifference = function(date1, date2){
var timeDifference = Math.abs(date2.getTime() - date1.getTime());
return Math.ceil(timeDifference / (1000 * 3600 * 24));//ms * seconds * hours
}
var difference = calculateDifference(new Date("7/16/2015"), new Date("7/20/2015"));
untested, but should work...
Using moment startDate and endDate:
function getBusinessDaysCount(startDate, endDate) {
let relativeDaySequence = [...Array(endDate.diff(startDate, "days")).keys()];
let daySequence = relativeDaySequence.map(relativeDay => {
let startDateClone = startDate.clone();
return startDateClone.add(relativeDay, "days");
});
return daySequence.reduce(
(dayCount, currentDay) => dayCount + (currentDay.day() === 0 || currentDay.day() === 6 ? 0 : 1),
0
);
}
Can Try this it will also work.
//fromDate is start date and toDate is end Date
var timeDiff = Math.abs(toDate.getTime() - fromDate.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)) ;
// var startDay = fromDate.getDay();
debugger;
var diffDayWeek = diffDays + fromDate.getDay();
var diffDiv = Math.floor(parseInt(diffDayWeek/7));
diffDiv *= 2; "Saturday and Sunday are Weekend
diffDays += 1 - diffDiv;

Get time left from now with giving time of tomorrow in 24 format in javascript

Happy new year everyone,,
I'm using this function to get the time left between today and giving date (Hours:Minutes) and it works fine...
function PrayerTimeLeft(prayerTime){
var today = new Date();
var prayerTimeDate = new Date();
prayerTimeDate.setHours(prayerTime.substring(0,2));
prayerTimeDate.setMinutes(prayerTime.substring(3,5));
var diffMs = (prayerTimeDate - today);
var diffHrs = Math.round((diffMs % 86400000) / 3600000);
var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000);
return {
getDiffMin:function(){
return diffMins;
},
getDiffHrs:function(){
return diffHrs;
}
};
}
I can use it like this:
var test = new PrayerTimeLeft("14:00"); // and today was 12:00 in 24 format
console.log(test.getDiffHrs()); //It will show 2 hours
I'm here trying to get how many left for a coming Prayer time, there are five Prayers: First: 5:00
Second: 11:42
Third: 14:26
Fourth: 16:50
Fifth: 18:07
My problem is if the current time (let's say it will 23:00) is between fifth and first one, here we are talking about tomorrow time which is between (5:00 & 18:07)
I can't realize this reverse things?
I have 3 suggestions:
Return only references to functions. Your pattern becomes messy with, let's say, 4+ methods.
If you are sure you'll get a string HH:MM, why don't you simply split it?
Avoid setting secondary variables just like you did. If you already have primary values (today and prayerTime) and you are able to derive various new measures (like hours, min, secs etc. left) leave your object as stateless as you can.
Some other patterns would suggest declaring functions AFTER the return statement (instead of declaring vars and anonymous functions)
function PrayerTimeLeft(prayerTime) {
var today = new Date();
var prayerTimeDate = new Date();
var setPrayerTime = function() {
var prayerHours = prayerTime.split(':')[0];
var prayerMin = prayerTime.split(':')[1];
if (today.getHours() >= prayerHours) {
prayerTimeDate.setDate(today.getDate() + 1);
}
prayerTimeDate.setHours(prayerHours);
prayerTimeDate.setMinutes(prayerMin);
};
var getDiffMin = function() {
return (prayerTimeDate - today) / 1000 / 60;
};
var getDiffHrs = function() {
return Math.floor((prayerTimeDate - today) / 1000 / 60 / 60);
};
setPrayerTime();
return {
getDiffMin: getDiffMin,
getDiffHrs: getDiffHrs
};
}
And testing:
var test = new PrayerTimeLeft("00:00"); // and today was 12:00 in 24 format
console.log(test.getDiffMin()); //It will show total minutes left
console.log(test.getDiffHrs()); //It will show total hours left (without minutes) 14:59 left will be shown as 14 hours left (15 hours would be more inaccurate).
EDIT: If you want to return HH:MM, here is a snippet with extra function.
function PrayerTimeLeft(prayerTime) {
var today = new Date();
var prayerTimeDate = new Date();
var setPrayerTime = function() {
var prayerHours = prayerTime.split(':')[0];
var prayerMin = prayerTime.split(':')[1];
if (today.getHours() >= prayerHours) {
prayerTimeDate.setDate(today.getDate() + 1);
}
prayerTimeDate.setHours(prayerHours);
prayerTimeDate.setMinutes(prayerMin);
};
var getDiffMin = function() {
return (prayerTimeDate - today) / 1000 / 60;
};
var getDiffHrs = function() {
return Math.floor((prayerTimeDate - today) / 1000 / 60 / 60);
};
var getDiffString = function() {
return Math.floor(getDiffMin() / 60) + ':' + getDiffMin() % 60;
}
setPrayerTime();
return {
getDiffMin: getDiffMin,
getDiffHrs: getDiffHrs,
getDiffString: getDiffString
};
}

What is the correct way to count the number of days between two dates in javascript [duplicate]

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 :) ");

How to calculate the number of days between two dates? [duplicate]

This question already has answers here:
How to calculate number of days between two dates?
(42 answers)
Closed 8 years ago.
I am calculating the number of days between the 'from' and 'to' date. For example, if the from date is 13/04/2010 and the to date is 15/04/2010 the result should be
How do I get the result using JavaScript?
const oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
const firstDate = new Date(2008, 1, 12);
const secondDate = new Date(2008, 1, 22);
const diffDays = Math.round(Math.abs((firstDate - secondDate) / oneDay));
Here is a function that does this:
function days_between(date1, date2) {
// The number of milliseconds in one day
const ONE_DAY = 1000 * 60 * 60 * 24;
// Calculate the difference in milliseconds
const differenceMs = Math.abs(date1 - date2);
// Convert back to days and return
return Math.round(differenceMs / ONE_DAY);
}
Here's what I use. If you just subtract the dates, it won't work across the Daylight Savings Time Boundary (eg April 1 to April 30 or Oct 1 to Oct 31). This drops all the hours to make sure you get a day and eliminates any DST problem by using UTC.
var nDays = ( Date.UTC(EndDate.getFullYear(), EndDate.getMonth(), EndDate.getDate()) -
Date.UTC(StartDate.getFullYear(), StartDate.getMonth(), StartDate.getDate())) / 86400000;
as a function:
function DaysBetween(StartDate, EndDate) {
// The number of milliseconds in all UTC days (no DST)
const oneDay = 1000 * 60 * 60 * 24;
// A day in UTC always lasts 24 hours (unlike in other time formats)
const start = Date.UTC(EndDate.getFullYear(), EndDate.getMonth(), EndDate.getDate());
const end = Date.UTC(StartDate.getFullYear(), StartDate.getMonth(), StartDate.getDate());
// so it's safe to divide by 24 hours
return (start - end) / oneDay;
}
Here is my implementation:
function daysBetween(one, another) {
return Math.round(Math.abs((+one) - (+another))/8.64e7);
}
+<date> does the type coercion to the integer representation and has the same effect as <date>.getTime() and 8.64e7 is the number of milliseconds in a day.
Adjusted to allow for daylight saving differences. try this:
function daysBetween(date1, date2) {
// adjust diff for for daylight savings
var hoursToAdjust = Math.abs(date1.getTimezoneOffset() /60) - Math.abs(date2.getTimezoneOffset() /60);
// apply the tz offset
date2.addHours(hoursToAdjust);
// The number of milliseconds in one day
var ONE_DAY = 1000 * 60 * 60 * 24
// Convert both dates to milliseconds
var date1_ms = date1.getTime()
var date2_ms = date2.getTime()
// Calculate the difference in milliseconds
var difference_ms = Math.abs(date1_ms - date2_ms)
// Convert back to days and return
return Math.round(difference_ms/ONE_DAY)
}
// you'll want this addHours function too
Date.prototype.addHours= function(h){
this.setHours(this.getHours()+h);
return this;
}
I have written this solution for another post who asked, how to calculate the difference between two dates, so I share what I have prepared:
// Here are the two dates to compare
var date1 = '2011-12-24';
var date2 = '2012-01-01';
// First we split the values to arrays date1[0] is the year, [1] the month and [2] the day
date1 = date1.split('-');
date2 = date2.split('-');
// Now we convert the array to a Date object, which has several helpful methods
date1 = new Date(date1[0], date1[1], date1[2]);
date2 = new Date(date2[0], date2[1], date2[2]);
// We use the getTime() method and get the unixtime (in milliseconds, but we want seconds, therefore we divide it through 1000)
date1_unixtime = parseInt(date1.getTime() / 1000);
date2_unixtime = parseInt(date2.getTime() / 1000);
// This is the calculated difference in seconds
var timeDifference = date2_unixtime - date1_unixtime;
// in Hours
var timeDifferenceInHours = timeDifference / 60 / 60;
// and finaly, in days :)
var timeDifferenceInDays = timeDifferenceInHours / 24;
alert(timeDifferenceInDays);
You can skip some steps in the code, I have written it so to make it easy to understand.
You'll find a running example here: http://jsfiddle.net/matKX/
From my little date difference calculator:
var startDate = new Date(2000, 1-1, 1); // 2000-01-01
var endDate = new Date(); // Today
// Calculate the difference of two dates in total days
function diffDays(d1, d2)
{
var ndays;
var tv1 = d1.valueOf(); // msec since 1970
var tv2 = d2.valueOf();
ndays = (tv2 - tv1) / 1000 / 86400;
ndays = Math.round(ndays - 0.5);
return ndays;
}
So you would call:
var nDays = diffDays(startDate, endDate);
(Full source at http://david.tribble.com/src/javascript/jstimespan.html.)
Addendum
The code can be improved by changing these lines:
var tv1 = d1.getTime(); // msec since 1970
var tv2 = d2.getTime();

How to calculate number of days between two dates?

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 :) ");

Categories

Resources