-1

I need to print out the days where it is Friday the 13th next year.

What would be a good way to do that, currently I have a loop that goes through the days in between 1/1/2019 and 12/31/2019 from this question: How do you iterate through every day of the year? however I do not know how to check if a day is a friday the 13th.

Please help.

My code:

using System;

class Program 
{
  static void Main(string[] args)
  {
    DateTime date = new DateTime(2019,01,01);
    DateTime end = new DateTime(2019,12,31);
    for(; date <= end; date = date.AddDays(1)) 
    {
      Console.WriteLine(date.ToString());

    } 
  }
}
  • 2
    Create a `DateTime` for the first day of the year. Call `AddDays(1)` in a loop until you get to Friday. Call `AddDays(7)` in a loop until you get to/past then end of the year and check the day of the month number of each Friday. No, I'm not going to write the code for you. It's up to you to take it from here. – jmcilhinney Sep 17 '18 at 02:42
  • search `DayOfWeek ` – Circle Hsiao Sep 17 '18 at 03:34

1 Answers1

4

Instead of checking all the days of the year you can just check if the 13th day of each month is a Friday.

Secondly, you could dynamically obtain the next year instead of hard coding it as 2019, you can do that using DateTime.Today.Year + 1.

Try something like this loop:

for (int i = 1; i <= 12; i++) {
  DateTime date = new DateTime(DateTime.Today.Year + 1, i, 13);
  if (date.DayOfWeek == DayOfWeek.Friday) {
    Console.WriteLine(date.ToString("dd\\t\\h MMMM yyyy") + " is a Friday");
  }
}

Output:

13th September 2019 is a Friday
13th December 2019 is a Friday
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40
  • 5
    You really ought not to be writing code for people who have not shown any initiative. Answering bad questions encourages more bad questions. That said, your idea of going per month is better than my idea of going per week. – jmcilhinney Sep 17 '18 at 02:43