I am working on a module (scheduler). If I add scheduler and I select 2 or many tuesdays from current date to schedule my task. And It will show my task on scheduler for coming 2 or many tuesdays. How can I code this.
To get 2 or many tuesdays from current date. C# or jquery
I have seen many codes but these are not fulfilling my condition.
Var date = new date()
CodePudding user response:
You can try this:
DateTime dtFrom = DateTime.Today; // any starting date
int NextWeekDay = 5; // 1=Sun, 7=sun, so look for Friday's
int HowMany = 3; // how many to get
NextWeekDay = NextWeekDay - (int)dtFrom.DayOfWeek;
if (NextWeekDay < 0)
NextWeekDay = 7;
DateTime dtStart = dtFrom.AddDays(NextWeekDay);
for (int i=0; i < HowMany; i )
{
DateTime MyDate = dtStart.AddDays(i * 7);
Debug.Print(MyDate.ToLongDateString());
}
output:
Friday, December 9, 2022
Friday, December 16, 2022
Friday, December 23, 2022
So, today is Saturday Dec 3rd, and I count/include today if the requested starting date is same date.
CodePudding user response:
To obtain 2 or many upcoming day of the week (e.g. Tuesday) dates from the current date to schedule, you can the concept in the console example below.
Demo: https://dotnetfiddle.net/UrUrS2
Pass to the ReturnNextNthWeekdaysOfMonth
function the following inputs:
- starting date e.g.
DateTime.Now
- day of the week e.g.
DayOfWeek.Tuesday
- amount of schedule dates to obtain e.g.
2
The result will be the dates to schedule.
public class Program
{
public static void Main()
{
var scheduleDates = ReturnNextNthWeekdaysOfMonth(
DateTime.Now, DayOfWeek.Tuesday, 2);
foreach (var date in scheduleDates) Console.WriteLine(date.ToString("f"));
}
private static IEnumerable<DateTime> ReturnNextNthWeekdaysOfMonth(
DateTime dt, DayOfWeek weekday, int amounttoshow = 4)
{
// Find the first future occurance of the day.
while (dt.DayOfWeek != weekday)
dt = dt.AddDays(1);
// Create the entire range of dates required.
return Enumerable.Range(0, amounttoshow).Select(i => dt.AddDays(i * 7));
}
}
Output:
Tuesday, 6 December, 2022 12:56 PM
Tuesday, 13 December, 2022 12:56 PM