c# 3rd working day excluding satuday and sunday - c#

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?

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

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

Related

How do I find the nth DayOfWeek for a given month?

I am trying to find the nth DayOfWeek for a given month (in a given year).
For example: I am looking for the 3rd Saturday of May (2019).
I failed to come up with a working solution using the DayOfWeek extension method. Do I have to loop through the entire month to find the third Saturday?
You could of course loop through the entire month but I think this is a more elegant way (taken from here):
private static DateTime FindTheNthDayOfWeek(int year, int month, int nthOccurrence, DayOfWeek dayOfWeek)
{
if (month < 1 || month > 12)
{
throw new ArgumentOutOfRangeException("Invalid month");
}
if (nthOccurrence < 0 || nthOccurrence > 5)
{
throw new ArgumentOutOfRangeException("Invalid nth occurrence");
}
var dt = new DateTime(year, month, 1);
while (dt.DayOfWeek != dayOfWeek)
{
dt = dt.AddDays(1);
}
dt = dt.AddDays((nthOccurrence - 1) * 7);
if (dt.Month != month)
{
throw new ArgumentOutOfRangeException(string.Format("The given month has less than {0} {1}s", nthOccurrence, dayOfWeek));
}
return dt;
}
This private method doesn't loop through the entire month but stops already once the first DayOfWeek has been found. Then you simply add a week for each nth occurrence (minus the already added week ;-) ).
If you talk about dates it should be related to some calendar, in my example Gregorian.
public static class DataTimeExt
{
public static IEnumerable<DateTime> TakeWhileInclusive(this DateTime value,
Func<DateTime, bool> func)
{
DateTime dt = value;
yield return dt; //[first
while (func(dt = dt.AddDays(1))) yield return dt; //in between
yield return dt; //last]
}
}
then you could just iterate through the dates until Sunday and then add 14 days.
var calendar = new GregorianCalendar();
var dates = new DateTime(2019, 5, 1, calendar)
.TakeWhileInclusive(dt => calendar.GetDayOfWeek(dt) != DayOfWeek.Sunday);
Console.WriteLine(dates.Last().AddDays(14));
This is simple and clean with no looping. Just a little arithmetic.
static DateTime? NthWeekDayOfMonth( int n, DayOfWeek dow, int year , int month)
{
DateTime startOfMonth = new DateTime( year, month, 1 ) ;
int offset = ( 7 + dow - startOfMonth.DayOfWeek ) % 7 ;
DateTime nthWeekDayOfMonth = startOfMonth
.AddDays( offset )
.AddDays( 7 * (n-1) )
;
bool isSameMonth = startOfMonth.Year == nthWeekDayOfMonth.Year
&& startOfMonth.Month == nthWeekDayOfMonth.Month
;
return isSameMonth
? nthWeekDayOfMonth
: (DateTime?) null
;
}
I created two extension methods, where one gets the next DayOfWeek from the date, optionally including the date itself, and the other for the previous DayOfWeek, with the same functionality.
public static DateTime Next(
this DateTime source,
DayOfWeek dayOfWeek,
bool considerSameDate
) => ( dayOfWeek - source.DayOfWeek) is var difference
&& difference < (considerSameDate ? 0 : 1)
? source.AddDays(difference + 7)
: source.AddDays(difference)
;
and
public static DateTime Previous(
this DateTime source,
DayOfWeek dayOfWeek,
bool considerSameDate
) => dayOfWeek == source.DayOfWeek
? ( considerSameDate ? source : source.AddDays(-7) )
: source.AddDays(
( dayOfWeek - source.DayOfWeek ) is var difference
&& difference > 0
? difference - 7
: difference
);
Having these, one can ask the questions you posed:
var x = new System.DateTime(2019, 5, 1).Next(System.DayOfWeek.Saturday, true).AddDays(14);
I create a new DateTime (2019-05-01), call Next with Saturday and consider 5/1 as a candidate, and then add 14 days, which makes it to the third Saturday of May, 2019.

How to count working 15 days and get enddate?

How to calculate actual working days of my when user checkin in hotel? I want to count working days only except Saturday and Sunday. Please check below function its count working days but in parameter I entered startdate and enddate.
I want send only startdate its automatically count 15 working days and return me enddate.
//Days count
public static double GetBusinessDays(DateTime startD, DateTime endD)
{
double calcBusinessDays =
1 + ((endD - startD).TotalDays * 5 -
(startD.DayOfWeek - endD.DayOfWeek) * 2) / 7;
if (endD.DayOfWeek == DayOfWeek.Saturday) calcBusinessDays--;
if (startD.DayOfWeek == DayOfWeek.Sunday) calcBusinessDays--;
return calcBusinessDays;
}
I want like this:
public static Datetime GetBusinessDays(DateTime startDate)
{
Datetime After15WorkingDaysDate;
return After15WorkingDaysDate;
}
Here are two methods.
The idea is to generate each date in the range, decide whether it is a Business Day, and only then add it to the result list.
GetBusinessDaysInRange returns a list of the dates of the Business Days between the given start and end date. End date is exclusive, i.e. if the end date is a Business Day, it will not be part of the result.
// Returns a list of the dates of the Business Days between the given start and end date
public static IEnumerable<DateTime> GetBusinessDaysInRange(DateTime startDate, DateTime endDate, DayOfWeek[] closedOn) {
if (endDate < startDate) {
throw new ArgumentException("endDate must be before startDate");
}
var businessDays = new List<DateTime>();
var date = startDate;
while (date < endDate) {
if (!closedOn.Contains(date.DayOfWeek)) {
businessDays.Add(date);
}
date = date.AddDays(1);
}
return businessDays;
}
GetFixedNumberOfBusinessDays returns a list of the dates of the Business Days from the given start with the given number of days (the method you asked for).
// Returns a list of the dates of the Business Days from the given start with the given number of days
public static IEnumerable<DateTime> GetFixedNumberOfBusinessDays(DateTime startDate, int numberOfBusinessDays, DayOfWeek[] closedOn) {
if (numberOfBusinessDays < 0) {
throw new ArgumentException("numberOfBusinessDays must be zero or positive.");
}
var businessDays = new List<DateTime>();
var date = startDate;
while (businessDays.Count() < numberOfBusinessDays) {
if (!closedOn.Contains(date.DayOfWeek)) {
businessDays.Add(date);
}
date = date.AddDays(1);
}
return businessDays;
}
The parameter DayOfWeek[] closedOn was introduced because you do not want to hardcode the days of the week that are not Business Days.
The return type was changed to IEnumerable<DateTime> so this method is more universal. If you only want the number of days and are not interested in the actual dates, just run a .Count() on the result. If you want the end date, call .Last().
.Net Fiddle with usage examples:
var closedOn = new DayOfWeek[] { DayOfWeek.Saturday, DayOfWeek.Sunday };
var start = new DateTime(2018, 07, 23);
var numberOfDays = 10;
var businessDays = GetFixedNumberOfBusinessDays(end, numberOfDays, closedOn);
int actualNumberOfBusinessDays = businessDays.Count(); // 10
DateTime endDate = businessDays.Last(); // Friday, August 3, 2018
It should be generic method. You can add different work day in another place.
public static DateTime AddWorkdays(this DateTime originalDate, int workDays)
{
DateTime tmpDate = originalDate;
while (workDays > 0)
{
tmpDate = tmpDate.AddDays(1);
if (tmpDate.DayOfWeek == DayOfWeek.Saturday ||
tmpDate.DayOfWeek == DayOfWeek.Sunday )
workDays--;
}
return tmpDate;
}
DateTime endDate = startDate.AddWorkdays(15);

Loop through current years month to next year month in c#

I am facing a problem, logic written in my program is below
while (lastDate.Month < DateTime.Today.Month - 1)//
{
lastDate= lastDate.AddMonths(1);
list.Add(lastDate);
}
This code is failing when lastDate month is Dec and i am executing this code in Jan or Feb of new year because 12 would never be greater then 1 0r 2.
I need to write a logic where my loop could traverse through Nov, Dec, Jan , Feb and so on.
I have written below code which is working however i am not getting clue to exit, loop should exit when difference between lastDate and todays date is 2 months.
if (lastDate.Month > DateTime.Today.Month && lastDate.Year < DateTime.Today.Year)
{
while (lastDate.Year <= DateTime.Today.Year)
{
lastDate= lastDate.AddMonths(1);
list.Add(lastDate);
}
}
Please help me in this
You will always add 12 months to the list, so you can use a for-loop:
for(var i = 0; i < 12; i++)
{
lastDate = lastDate.AddMonths(1);
list.Add(lastDate);
}
As you know how many times you have to add one month, there is no need to have a condition depending on the month and year, but only a counter to execute this code exactly 12 times.
This may helps:
DateTime lastDate = DateTime.ParseExact("01/12/12", "dd/MM/yy", System.Globalization.CultureInfo.InvariantCulture);
List<DateTime> result = new List<DateTime>();
//iterate until the difference is two months
while (new DateTime((DateTime.Today - lastDate).Ticks).Month >= 2)
{
result.Add(lastDate);
lastDate = lastDate.AddMonths(1);
}
//result: 12/1/2012
// 1/1/2013
// 2/1/2013
// 3/1/2013
Hopefully this will solve your problem:
DateTime lastDate = new DateTime(2012, 1, 1);
List<DateTime> list = new List<DateTime>();
while (lastDate < (DateTime.Today.AddMonths(-3))) //difference between today and lastDate should be 2 month
{
lastDate = lastDate.AddMonths(1);
list.Add(lastDate);
}
This will add 12 DateTimes from lastDate to your list :)
list.AddRange(Enumerable.Range(0,12).Select(v => lastDate = lastDate.AddMonths(1)));

Get Day For Previous Month

I have a what seems like simple date issue and I just can't wrap my head around trying to get it efficiently... I basically need to get the previous months date for a specific day.
For example: If today is the 3rd Thursday of the month, I want to get the 3rd Thursday's date of last month. Its important that its based of the number of the day...ie: First Monday, 4th Friday, 2nd Wednesday, etc.
What's the best way to get this done?
BTW...If there is not an equivalent previous months day that is fine. I can handle that. Also, currently I am counting the number or days ("Mondays", "Tuesdays", etc) manually to figure this out. I was just hoping there is a more elegant way to do it.
Here's what I would do:
static DateTime? GetLastMonthSameNthDayOfWeek(DateTime date)
{
int nth = (date.Day-1) / 7; // returns 0 if 1st, 1 if 2nd...
var prevMonthDay = date.AddMonths(-1);
// find the first date of month having the same day of week
var d = new DateTime(prevMonthDay.Year, prevMonthDay.Month, 1);
while(d.Day <= 7)
{
if (d.DayOfWeek == date.DayOfWeek)
break;
d = d.AddDays(1);
}
// go to nth day of week
d = d.AddDays(7 * nth);
// if we have passed the current month, there's no nth day of week
if (d.Month != prevMonthDay.Month)
return null;
return d;
}
Usage example:
// 3rd wednesday of August 2012
var a = new DateTime(2012, 8, 15);
var aPrev = GetLastMonthSameNthDayOfWeek(a);
// aPrev = July 18th 2012 (i.e. the 3rd wednesday of July 2012)
// 5th wednesday of August 2012
var b = new DateTime(2012, 8, 15);
var bPrev = GetLastMonthSameNthDayOfWeek(b);
// bPrev = null, because there's no 5th wednesday of July 2012
N.B. :
getting the ordinal position of the day of week inside a month is really easy:
int nth = ((date.Day-1) / 7) + 1; // 1 -> 1st, 2 -> 2nd, 3 -> 3rd ...
As I couldn't find a built-in way, I've written this simple extension method for DateTime, check it out:
public static class DateTimeExtension
{
public static DateTime GetPositionalDate(this DateTime BaseDate, DayOfWeek WeekDay, int position)
{
if (position < 1)
{
throw new Exception("Invalid position");
}
else
{
DateTime ReturnDate = new DateTime(BaseDate.Year, BaseDate.Month, BaseDate.Day);
int PositionControl = 1;
bool FoundDate = false;
while(ReturnDate.DayOfWeek != WeekDay)
{
ReturnDate = ReturnDate.AddDays(1);
}
while (!FoundDate && PositionControl <= position)
{
PositionControl++;
if (PositionControl == position)
{
FoundDate = true;
}
else
{
ReturnDate = ReturnDate.AddDays(7);
}
}
if (FoundDate)
{
return ReturnDate;
}
else
{
throw new Exception("Date not found");
}
}
}
}
Usage:
DateTime lastMonth = DateTime.Now.GetPositionalDate(DayOfWeek.Sunday, 2);
Regards
There is no, by default, a way that .Net understand this specific logic for dates. So using the following, you can get what you're looking for:
var now = DateTime.Now.Date;
Use DateTime.AddMonth(-1) to get last month.
Use DateTime.AddDays(now.Days * -1 + 1) to get the first of the month.
Use DateTime.DayOfWeek to determine the day and subtract or add days as necessary
Ok, what you can do is determine the day of the week of the first day of the month last month, take the difference between the day of the week you want and that day of the week, then add 7 * the weeks you want (less one week)...
// Let's get the 3rd Friday of last month:
// get starting date
DateTime date = new DateTime();
// get first day of last month
DateTime firstOfLastMonth = date.AddMonths(-1).AddDays(-1 * (date.Day + 1));
// subtract out the day of the week (get the previous Sunday, even if it is last month)
DateTime justBeforeMonth = firstOfLastMonth.AddDays((int)firstOfLastMonth.DayOfWeek);
// Add in the DayOfWeek number we are looking for
DateTime firstFridayOfMonth = justBeforeMonth.AddDays(DayOfWeek.Friday);
// if we are still in last month, add a week to get into this month
if (firstFridayOfMonth.Month != date.AddMonth(-1).Month) { firstFridayOfMonth.AddDays(7); }
// add in 2 weeks to get the third week of the month
DateTime thirdFridayOfMonth = firstFridayOfMonth.AddDays(14);
Here's the solution I came up with. If the day doesn't exist (e.g. 8th Saturday), GetDate() will return null:
{
DateTime lastMonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(-1);
DateTime? date = GetDate(lastMonth.Month, lastMonth.Year, DayOfWeek.Thursday, 2);
}
private static DateTime? GetDate(int month, int year, DayOfWeek dayOfWeek, int which)
{
DateTime firstOfMonth = new DateTime(year, month, 1);
DateTime date;
for (date = firstOfMonth; date.DayOfWeek != dayOfWeek; date = date.AddDays(1))
;
date = date.AddDays(7 * (which - 1));
return date.Month == month && date.Year == year ? (DateTime?)date : null;
}

How to get last Friday of month(s) using .NET

I have a function that returns me only the fridays from a range of dates
public static List<DateTime> GetDates(DateTime startDate, int weeks)
{
int days = weeks * 7;
//Get the whole date range
List<DateTime> dtFulldateRange = Enumerable.Range(-days, days).Select(i => startDate.AddDays(i)).ToList();
//Get only the fridays from the date range
List<DateTime> dtOnlyFridays = (from dtFridays in dtFulldateRange
where dtFridays.DayOfWeek == DayOfWeek.Friday
select dtFridays).ToList();
return dtOnlyFridays;
}
Purpose of the function: "List of dates from the Week number specified till the StartDate i.e. If startdate is 23rd April, 2010 and the week number is 1,then the program should return the dates from 16th April, 2010 till the startddate".
I am calling the function as:
DateTime StartDate1 = DateTime.ParseExact("20100430", "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);
List<DateTime> dtList = Utility.GetDates(StartDate1, 4).ToList();
Now the requirement has changed a bit. I need to find out only the last Fridays of every month.
The input to the function will remain same.
You already have the list of Fridays in the given range. Now just query this again like this:
List<DateTime> lastFridays = (from day in fridays
where day.AddDays(7).Month != day.Month
select day).ToList<DateTime>();
Hope this helps.
Just a small improvement on Sarath's answer, for those (like me) who step into this question
private DateTime GetLastFridayOfTheMonth(DateTime date)
{
var lastDayOfMonth = new DateTime(date.Year, date.Month, DateTime.DaysInMonth(date.Year, date.Month));
while (lastDayOfMonth.DayOfWeek != DayOfWeek.Friday)
lastDayOfMonth = lastDayOfMonth.AddDays(-1);
return lastDayOfMonth;
}
Here's an extension method we are using.
public static class DateTimeExtensions
{
public static DateTime GetLastFridayInMonth(this DateTime date)
{
var firstDayOfNextMonth = new DateTime(date.Year, date.Month, 1).AddMonths(1);
int vector = (((int)firstDayOfNextMonth.DayOfWeek + 1) % 7) + 1;
return firstDayOfNextMonth.AddDays(-vector);
}
}
Below is the MbUnit test case
[TestFixture]
public class DateTimeExtensionTests
{
[Test]
[Row(1, 2011, "2011-01-28")]
[Row(2, 2011, "2011-02-25")]
...
[Row(11, 2011, "2011-11-25")]
[Row(12, 2011, "2011-12-30")]
[Row(1, 2012, "2012-01-27")]
[Row(2, 2012, "2012-02-24")]
...
[Row(11, 2012, "2012-11-30")]
[Row(12, 2012, "2012-12-28")]
public void Test_GetLastFridayInMonth(int month, int year, string expectedDate)
{
var date = new DateTime(year, month, 1);
var expectedValue = DateTime.Parse(expectedDate);
while (date.Month == month)
{
var result = date.GetLastFridayInMonth();
Assert.AreEqual(expectedValue, result);
date = date.AddDays(1);
}
}
}
Check what day of the week the first day of the next month is on, then subtract enough days to get a Friday.
Or, if you already have a list of Fridays, return only those for which adding 7 days gives a date in the next month.
Based on DeBorges answer, here is an extension to get any specific Day
public static DateTime GetLastSpecificDayOfTheMonth(this DateTime date, DayOfWeek dayofweek)
{
var lastDayOfMonth = new DateTime(date.Year, date.Month, DateTime.DaysInMonth(date.Year, date.Month));
while (lastDayOfMonth.DayOfWeek != dayofweek)
lastDayOfMonth = lastDayOfMonth.AddDays(-1);
return lastDayOfMonth;
}
Call the below function by sending the date as parameter, in which it extracts the month and year from the date parameter and returns the last Friday of that month
public DateTime GetLastFridayOfMonth(DateTime dt)
{
DateTime dtMaxValue = DateTime.MaxValue;
DateTime dtLastDayOfMonth = new DateTime(dt.Year, dt.Month, DateTime.DaysInMonth(dt.Year, dt.Month));
while (dtMaxValue == DateTime.MaxValue)
{
// Returns if the decremented day is the fisrt Friday from last(ie our last Friday)
if (dtMaxValue == DateTime.MaxValue && dtLastDayOfMonth.DayOfWeek == DayOfWeek.Friday)
return dtLastDayOfMonth;
// Decrements last day by one
else
dtLastDayOfMonth = dtLastDayOfMonth.AddDays(-1.0);
}
return dtLastDayOfMonth;
}

Categories