I have a code that gives me the Nth day of the month. between two dates. Now what I want is to check if the Start date is not the Nth day of the month, move the start date to the following month same first day. For example.
a user entered Start date of 06/27/2019 which is a Thursday but want the first day of the month for Monday which was 06/3/2019, which is already passed so the new start date should be 07/1/2019. How to I get my code to achieve this.
Below is my complete code.
a user entered Start date of 06/27/2019 which is a Thursday but want the first day of the month for Monday which was 06/3/2019, which is already passed so the new start date should be 07/1/2019. How to I get my code to achieve this.
Below is my complete code.
C#:
class Program
{
public class BusinessWeekDays
{
public DateTime Monday;
public DateTime Sunday;
}
public static List<DateTime> GetDatesByOrdinalDayV2(DateTime startDate, DateTime endDate, DayOfWeek dayOfWeek,
int ordinal)
{
var foundDates = new List<DateTime>();
ordinal = Math.Min(Math.Max(ordinal, 1), 5);
while (startDate < endDate)
{
var month = startDate.Month;
var workingDate = new DateTime(startDate.Year, month, 1);
workingDate = (int)workingDate.DayOfWeek > (int)dayOfWeek
? workingDate.AddDays(7 - (int)workingDate.DayOfWeek + (int)dayOfWeek)
: workingDate.AddDays((int)dayOfWeek - (int)workingDate.DayOfWeek);
workingDate = workingDate.AddDays((ordinal - 1) * 7);
workingDate = workingDate.Month != month ? workingDate.AddDays(-7) : workingDate;
foundDates.Add(workingDate);
startDate = startDate.AddMonths(1);
}
return foundDates;
}
static void Main(string[] args)
{
var StartDate = DateTime.Parse("06/27/2019");
var SeriesEndDate = DateTime.Parse("09/30/2019");
var months = new List<BusinessWeekDays>();
var secondTuesday = GetDatesByOrdinalDayV2(StartDate, SeriesEndDate, DayOfWeek.Monday, 1);
var dateStrings = secondTuesday
.Select(dateTime => dateTime.ToString("d MMM yyyy")).ToList();
foreach (var date in dateStrings)
{
if (StartDate.DayOfWeek != DayOfWeek.Monday)----> start date is not Monday
{
months.Add(new BusinessWeekDays
{
Monday = Convert.ToDateTime(date).AddMonths(1),----Start Monday 7/1/2019
Sunday = Convert.ToDateTime(date).AddMonths(1).AddDays(7)
});
Console.WriteLine(months);
}
else
{
months.Add(new BusinessWeekDays
{
Monday = Convert.ToDateTime(date),
Sunday = Convert.ToDateTime(date).AddDays(7)
});
}
}
}