0

I want to get a next backup date using (day-of-week) monthly for a scheduled backup.

If I took a backup on Monday, second week, Jan-2019, then Next backup date should be Monday in the second week of February-2019.

So, How can we get the specific day as per the given week for every coming month?

Now I'm getting the next backup month but I'm not sure how we get the same Day in a specfic week.

Vipin
  • 27
  • 1
  • 5
  • https://stackoverflow.com/questions/5421972/how-to-find-the-3rd-friday-in-a-month-with-c – Drag and Drop Apr 19 '19 at 11:58
  • But the above link has given the same day of next month, it does not depend on the week. In my case, I have to find the same day in the same week in next month. E.g. If someone selected Monday in the Second week of the month, then we need to find Monday in the second week of the next month. This date will be the next backup date. – Vipin Apr 19 '19 at 12:06

2 Answers2

1

You should create an extension method for DateTime class.

public static DateTime NthOf(this DateTime CurDate, int Occurrence , DayOfWeek Day)
 {
     var fday = new DateTime(CurDate.Year, CurDate.Month, 1);

     var fOc = fday.DayOfWeek == Day ? fday : fday.AddDays(Day - fday.DayOfWeek);

     if (fOc.Month < CurDate.Month) Occurrence = Occurrence+1;
     return fOc.AddDays(7 * (Occurrence - 1));
 }

And use

new DateTime().NthOf(2, DayOfWeek.Monday))

Refer: How to calculate 2nd Friday of Month in C#

Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62
0

Why dont you get the DayOfTheYear and just add 7 to it. Something like this:

 var dateTime = DateTime.Now;
 var dayOfYear = dateTime.DayOfYear;
 var nextDate = dateTime.AddDays(dayOfYear + 7);
 Console.WriteLine(nextDate);

Since the next backup day is the same day, which means just add 7 to it. You will have to manage the last week of year though in this case

Praneet Nadkar
  • 823
  • 7
  • 16