Find Friday the 13th days in next calendar year

1563 views c#
5

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());

    } 
  }
}

answered question

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.

2 Answers

2

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

posted this
13

// your date loop starts here
DateTime dt = new DateTime(--your_date--);
DayOfWeek day = dt.DayOfWeek;

if(day==DayOfWeek.FRIDAY && your_day_counter==13)
    // It's Fri the 13th !!
// Your loop ends here 

posted this

Have an answer?

JD

Please login first before posting an answer.