TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Kwasi Denkyira
1.5k
197
14.8k
I want to generate a list of weekly business dates
Feb 22 2019 1:44 PM
I want to generate a list of weekly business dates between two dates excluding weekends and holidays. I have managed to exclude the Weekends and created a routine for the holidays. Now I need to exclude the holidays. Below is my code.
using
System;
using
System.Collections.Generic;
using
System.Linq;
namespace
SeriesTest
{
class
Program
{
public
class
BusinessWeekDays
{
public
DateTime Monday;
public
DateTime Sunday;
}
private
static
List Holidays =
new
List()
{
new
DateTime(1, 1, 1),
//New Year Day
new
DateTime(1, 5, 1),
//Labour Day
new
DateTime(1, 7, 4),
//Independence Day
new
DateTime(1, 3, 1),
//Martin Luther King Jr. Day
new
DateTime(1, 3, 2),
//Presidents Day
new
DateTime(1, 12, 25),
//Christmas
new
DateTime(1, 5, 5),
//Memorial Day
new
DateTime(1, 9, 1),
//Labor Day
new
DateTime(1, 10, 2),
//Columbus Day
new
DateTime(1, 11, 4),
//Columbus Day
};
private
static
bool
IsHoliday(DateTime value, List holidays =
null
)
{
if
(
null
== holidays)
holidays = Holidays;
return
(value.DayOfWeek == DayOfWeek.Sunday) ||
(value.DayOfWeek == DayOfWeek.Saturday) ||
holidays.Any(holiday => holiday.Day == value.Day &&
holiday.Month == value.Month);
}
public
static
int
BusinessDays(DateTime fromDate, DateTime toDate, List holidays =
null
)
{
int
result = 0;
for
(var date = fromDate;
date < toDate.Date;
date = date.AddDays(1))
if
(!IsHoliday(date, holidays))
result += 1;
return
result;
}
static
void
Main(
string
[] args)
{
var StartDate = DateTime.Parse(
"02/12/2019"
);
var SeriesEndDate = DateTime.Parse(
"12/31/2025"
);
var holidays =
new
List();
var firstMonday = Enumerable.Range(0, 7)
.SkipWhile(x => StartDate.AddDays(x).DayOfWeek != DayOfWeek.Monday)
.Select(x => StartDate.AddDays(x))
.First();
var ts = (SeriesEndDate - firstMonday);
var dates =
new
List();
for
(var i = 0; i < ts.Days; i += 7)
{
//Remove holidays. Weekend already removed here
if
(BusinessDays(StartDate, SeriesEndDate, holidays) != 0)
{
dates.Add(
new
BusinessWeekDays { Monday = firstMonday.AddDays(i), Sunday = firstMonday.AddDays(i + 9) });
}
}
Console.WriteLine(dates);
}
}
}
Reply
Answers (
1
)
"Hello World " focused
Create a Windows application that can be used to input a use