Reputation: 13
private void btnDateTime_Click(object sender, EventArgs e)
{
DateTime trdCurrentMonth = DateTime.Today.AddDays(-(DateTime.Today.Day - 3));
if (trdCurrentMonth !=
DateTime.Today.AddDays(-(DateTime.Today.Day)) &&
trdCurrentMonth != DateTime.Today.AddDays(-(DateTime.Today.Day - 1)))
{
MessageBox.Show(trdCurrentMonth.ToString());
}
}
How do I get the 3rd working day of current month, excluding Saturday and Sunday?
Upvotes: 1
Views: 244
Reputation: 16956
Get weekdays in a first 10 calendar dates and Skip
2
to get the third working day in a month.
DateTime dt = new DateTime(2016,6,1); // 1st Day of the Month.
var thirdWorkingDay = Enumerable.Range(0,10)
.Select(x=> dt.AddDays(x))
.Where(x=> x.DayOfWeek != DayOfWeek.Sunday && x.DayOfWeek != DayOfWeek.Saturday)
.Skip(2)
.FirstOrDefault() ;
Check this Demo
Upvotes: 2
Reputation: 29006
I prefer you to keep a List of DayOfWeek
to represent the holidays(here Saturday and Sunday). we can easily check whether the day is Saturday or Sunday. Then the first line will find the First day of the current month, Iterate through the days until we find the third working day. Now consider the code:
List<DayOfWeek> holydays = new List<DayOfWeek>() { DayOfWeek.Sunday, DayOfWeek.Saturday };
DateTime firstDayOfMonth = new DateTime(DateTime.Now.Date.Year, DateTime.Now.Date.Month, 1); // first day of month
int thirdDay = 1;
int addDay = 0;
while (thirdDay <= 3)
{
if (!holydays.Contains(firstDayOfMonth.AddDays(addDay++).DayOfWeek))
{
thirdDay++;
}
}
DateTime thirdWorkingDay = firstDayOfMonth.AddDays(--addDay);
This will give
03/06/2016 for june - 2016
05/07/2016 for july- 2016
Upvotes: 1