Find day difference between two dates (excluding weekend days)
Maybe someone else can help you converting this function into JQuery's framework...
I found this function here.
function calcBusinessDays(dDate1, dDate2) { // input given as Date objects var iWeeks, iDateDiff, iAdjust = 0; if (dDate2 < dDate1) return -1; // error code if dates transposed var iWeekday1 = dDate1.getDay(); // day of week var iWeekday2 = dDate2.getDay(); iWeekday1 = (iWeekday1 == 0) ? 7 : iWeekday1; // change Sunday from 0 to 7 iWeekday2 = (iWeekday2 == 0) ? 7 : iWeekday2; if ((iWeekday1 > 5) && (iWeekday2 > 5)) iAdjust = 1; // adjustment if both days on weekend iWeekday1 = (iWeekday1 > 5) ? 5 : iWeekday1; // only count weekdays iWeekday2 = (iWeekday2 > 5) ? 5 : iWeekday2;
// calculate differnece in weeks (1000mS * 60sec * 60min * 24hrs * 7 days = 604800000) iWeeks = Math.floor((dDate2.getTime() - dDate1.getTime()) / 604800000)
if (iWeekday1 < iWeekday2) { //Equal to makes it reduce 5 days iDateDiff = (iWeeks * 5) + (iWeekday2 - iWeekday1) } else { iDateDiff = ((iWeeks + 1) * 5) - (iWeekday1 - iWeekday2) }
iDateDiff -= iAdjust // take into account both days on weekend
return (iDateDiff + 1); // add 1 because dates are inclusive}
var date1 = new Date("August 11, 2010 11:13:00");var date2 = new Date("August 16, 2010 11:13:00");alert(calcBusinessDays(date1, date2));
Calculate difference between two dates excluding weekends in python?
Try converting string into date using the format of your date using pd.to_datetime()
use np.busday_count
to find difference between days excluding the weekends
import pandas as pd
import numpy as np
date1 = "01/07/2019"
date2 = "08/07/2019"
date1 = pd.to_datetime(date1,format="%d/%m/%Y").date()
date2 = pd.to_datetime(date2,format="%d/%m/%Y").date()
days = np.busday_count( date1 , date2)
print(days)
5
incase you want to provide holidays
holidays = pd.to_datetime("04/07/2019",format="%d/%m/%Y").date()
days = np.busday_count( start, end,holidays=[holidays] )
print(days)
4
Find day difference between two datetimes (excluding weekend days) in Python?
Try it with scikits.timeseries:
import scikits.timeseries as ts
import datetime
a = datetime.datetime(2011,8,1)
b = datetime.datetime(2011,8,29)
diff_business_days = ts.Date('B', b) - ts.Date('B', a)
# returns 20
or with dateutil:
import datetime
from dateutil import rrule
a = datetime.datetime(2011,8,1)
b = datetime.datetime(2011,8,29)
diff_business_days = len(list(rrule.rrule(rrule.DAILY,
dtstart=a,
until=b - datetime.timedelta(days=1),
byweekday=(rrule.MO, rrule.TU, rrule.WE, rrule.TH, rrule.FR))))
scikits.timeseries look depricated : http://pytseries.sourceforge.net/
With pandas instead someone can do :
import pandas as pd
a = datetime.datetime(2015, 10, 1)
b = datetime.datetime(2015, 10, 29)
diff_calendar_days = pd.date_range(a, b).size
diff_business_days = pd.bdate_range(a, b).size
Calculate working days between two dates in Javascript excepts holidays
The easiest way to achieve it is looking for these days between your begin and end date.
Edit: I added an additional verification to make sure that only working days from holidays
array are subtracted.
$(document).ready(() => {
$('#calc').click(() => {
var d1 = $('#d1').val();
var d2 = $('#d2').val();
$('#dif').text(workingDaysBetweenDates(d1,d2));
});
});
let workingDaysBetweenDates = (d0, d1) => {
/* Two working days and an sunday (not working day) */
var holidays = ['2016-05-03', '2016-05-05', '2016-05-07'];
var startDate = parseDate(d0);
var endDate = parseDate(d1);
// Validate input
if (endDate <= startDate) {
return 0;
}
// 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);
days -= weeks * 2;
// Handle special cases
var startDay = startDate.getDay();
var endDay = endDate.getDay();
// Remove weekend not previously removed.
if (startDay - endDay > 1) {
days -= 2;
}
// Remove start day if span starts on Sunday but ends before Saturday
if (startDay == 0 && endDay != 6) {
days--;
}
// Remove end day if span ends on Saturday but starts after Sunday
if (endDay == 6 && startDay != 0) {
days--;
}
/* Here is the code */
holidays.forEach(day => {
if ((day >= d0) && (day <= d1)) {
/* If it is not saturday (6) or sunday (0), substract it */
if ((parseDate(day).getDay() % 6) != 0) {
days--;
}
}
});
return days;
}
function parseDate(input) {
// Transform date from text to date
var parts = input.match(/(\d+)/g);
// new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])
return new Date(parts[0], parts[1]-1, parts[2]); // months are 0-based
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="d1" value="2016-05-02"><br>
<input type="text" id="d2" value="2016-05-08">
<p>Working days count: <span id="dif"></span></p>
<button id="calc">Calc</button>
<p>
Now it shows 5 days, but I need for example add holidays
3 and 5 May (2016-05-03 and 2016-05-05) so the result will be 3 working days
</p>
Difference between two dates excluding weekends
Another option is to create a dates sequence, exclude weekends and to compute its length.
library(chron)
length(myDays[!is.weekend(myDays)])
Here an example:
library(chron)
myDays <-
seq.Date(to = as.Date('01.05.2014', format="%d.%m.%Y"),
from=as.Date('01.01.2014', format = "%d.%m.%Y"),by=1)
length(myDays)
length(myDays[!is.weekend(myDays)])
EDIT
You should vectorize your function in order to use it with vectors.
getDuration <- function(d1, d2,fmt="%d.%m.%Y") {
myDays <- seq.Date(to = as.Date(d2, format=fmt),
from = as.Date(d1, format =fmt),
by = 1)
length(myDays[!is.weekend(myDays)]
}
Here I am using mapply
:
mapply(getDuration ,issues$created_on,issues$close_date)
Related Topics
Socket.Io 1.X: Use Websockets Only
Property 'Value' Does Not Exist on Type Eventtarget in Typescript
How to Get the Index of an Array in a Meteor Template Each Loop
How to Read a Text File from Server Using JavaScript
How to Get the Last Character of a String
Jquery .Find() Doesn't Return Data in Ie But Does in Firefox and Chrome
How to JSON Stringify a JavaScript Date and Preserve Timezone
[Vue Warn]: Property or Method Is Not Defined on the Instance But Referenced During Render
How to Remove a Class from Elements in Pure JavaScript
Reactjs Syntheticevent Stoppropagation() Only Works with React Events
How to Remove an Object from an Array with JavaScript
Getting Image Dimensions Using JavaScript File API
How to Persist a Es6 Map in Localstorage (Or Elsewhere)
Capture Click on Div Surrounding an Iframe
JavaScript Return Number of Days,Hours,Minutes,Seconds Between Two Dates
How to Detect Timeout on an Ajax (Xmlhttprequest) Call in the Browser