Get Date Range Between Two Dates Excluding Weekends

Get date range between two dates excluding weekends

For PHP >= 5.3.0, use the DatePeriod class. It's unfortunately barely documented.

$start = new DateTime('6/30/2010');
$end = new DateTime('7/6/2010');
$oneday = new DateInterval("P1D");

$days = array();
$data = "7.5";

/* Iterate from $start up to $end+1 day, one day in each iteration.
We add one day to the $end date, because the DatePeriod only iterates up to,
not including, the end date. */
foreach(new DatePeriod($start, $oneday, $end->add($oneday)) as $day) {
$day_num = $day->format("N"); /* 'N' number days 1 (mon) to 7 (sun) */
if($day_num < 6) { /* weekday */
$days[$day->format("Y-m-d")] = $data;
}
}
print_r($days);

I want to get all dates between two dates excluding weekends in jquery

The below code will iterate across all days in a given time frame and push the dates to an array if the day isn't a Saturday or Sunday. It doesn't account for public holidays and uses Vanilla JS (no jQuery needed.)

As you can see, I use .getDay() to determine whether what day of the week a given date is and check that it doesn't equal 6 (Saturday) or 0 (Sunday).

I then push it to the dates array to be used as you see fit. The reason I use .push(new Date(current)) instead of simply .push(current) is because the .setDate function replaces the value that variable points to and would result in an array full of the same date x amount of times without it.

The current variable could be removed altogether and the code changed to use the start variable but I like to create a new one just for readability.

const getBusinessDays = (startDate, endDate) => {
const start = new Date(startDate);
const end = new Date(endDate);
const current = start;
const dates = [];

while (current <= end) {
if (current.getDay() !== 6 && current.getDay() !== 0) {
dates.push(new Date(current));
}

current.setDate(current.getDate() + 1);
}

return dates;
}

const businessDays = getBusinessDays('10-01-2019', '11-29-2019');

console.log(businessDays);

i want to get all dates exclude weekends between two dates in python

Using date.weekday()

Return the day of the week as an integer, where Monday is 0 and Sunday
is 6.

from datetime import timedelta, date

def daterange(date1, date2):
for n in range(int ((date2 - date1).days)+1):
yield date1 + timedelta(n)

start_dt = date(2019,1,21)
end_dt = date(2019,2,4)

weekdays = [5,6]
for dt in daterange(start_dt, end_dt):
if dt.weekday() not in weekdays: # to print only the weekdates
print(dt.strftime("%Y-%m-%d"))

EDIT:

Using date.isoweekday():

Return the day of the week as an integer, where Monday is 1 and Sunday
is 7.

weekdays = [6,7]
for dt in daterange(start_dt, end_dt):
if dt.isoweekday() not in weekdays:
print(dt.strftime("%Y-%m-%d"))

OUTPUT:

2019-01-21
2019-01-22
2019-01-23
2019-01-24
2019-01-25
2019-01-28
2019-01-29
2019-01-30
2019-01-31
2019-02-01
2019-02-04

Query between two dates exclude weekends and holidays in php

You didn't say, so I will assume that the weekend part is working. Just check the $holidays array:

foreach(new DatePeriod($start, $day, $end->add($day)) as $k) {
$dnm = $k->format("N");
$key = $k->format("Y-m-d")

if($dnm < 6 && !in_array($key, $holidays)) {
$days[$key] = $duration->format("%H:%I:%S");
}
}

Number of days in date range, excluding weekends and other dates, in C#

Here's one example that includes the excluded dates, weekends, and looping. I did change the string excludeDates to a List though. Some null checking should be added.

    public static int DaysLeft(DateTime startDate, DateTime endDate, Boolean excludeWeekends, List<DateTime> excludeDates)
{
int count = 0;
for (DateTime index = startDate; index < endDate; index = index.AddDays(1))
{
if (excludeWeekends && index.DayOfWeek != DayOfWeek.Sunday && index.DayOfWeek != DayOfWeek.Saturday)
{
bool excluded = false; ;
for (int i = 0; i < excludeDates.Count; i++)
{
if (index.Date.CompareTo(excludeDates[i].Date) == 0)
{
excluded = true;
break;
}
}

if (!excluded)
{
count++;
}
}
}

return count;
}

EDIT: I do want to point out that I would consider this the quick and dirty method - if you didn't have to do this often. If you're performing this a lot and the distance between the startDate and endDate is rather large it would be much better to do the math as stated in one of the other answers. This is suggested in order to get a feel for iterating dates.

Generate a list of weekly business dates between two dates excluding weekends and holidays

It looks like you already have everything you need, but holidays is never set to your Holidays. Change the line below so that holidays is set to null. Then it will hit the null check in IsHoliday and be set properly.

var holidays = new List<DateTime>();

Should be:

var holidays = null;

Number of hours between two dates, excluding weekend

An additional library is needed for my answer (NumPy)

Key elements:

  1. numpy.busday_count to count the number of weekdays
  2. datetime.timedelta(1) to omit starting day (to be checked through if-else to count for minutes)
  3. isoweekday() returns value between 1 and 7, 1 being Monday and 7 Sunday

Steps:

  1. Skip the starting and ending days and find valid in-between days. Multiply by 24 (total hours per day)
  2. Check if starting day is a weekday and calculate the total hours remaining to end that date
  3. Check if the ending day is a weekday and calculate the total hours passed in that day
import datetime
import numpy as np

start_time = datetime.datetime(2021, 7, 1, 22, 45, 25)
end_time = datetime.datetime(2021, 7, 15, 10, 00, 00)
#Step 1.
total_hours=np.busday_count(start_time.date()+datetime.timedelta(1),end_time.date())*24 #already not counting last date
#Step2.
if start_time.isoweekday() in range(1, 6):
total_hours=total_hours+24-start_time.hour-start_time.minute/60-start_time.second/3600
#Step 3.
if end_time.isoweekday() in range(1, 6):
total_hours=total_hours+end_time.hour+end_time.minute/60+end_time.second/3600
print(total_hours)
output: 227.24305555555554

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


Related Topics



Leave a reply



Submit