2

So I have a very small code that I am working on as I am new to C#. I am looking to have it ask for the year - I.E - 2020 - and Provide the Month and day I have set behind in code. So for example. I am looking to pull - the 2nd Sunday after the 2nd Tuesday of every month. I have a code that does that now, but I have to change my code for each year. Is there a way to just type in the year and get those dates?

I am just unsure how to go about doing this.

Console.WriteLine("Insert Year");
string name =  Console.ReadLine();
for (int mth = 1; mth <= 12; mth++)
{
    DateTime dt = new DateTime(2019, mth, 20);
    while (dt.DayOfWeek != DayOfWeek.Sunday)
        dt = dt.AddDays(1);
    Console.WriteLine(dt.ToLongDateString());
}
Console.ReadLine();  
AbdelAziz AbdelLatef
  • 3,650
  • 6
  • 24
  • 52
Ngarda
  • 21
  • 1
  • Assuming you typed "2019" in the input, then `DateTime dt = new DateTime(name, mth, 20);` would do the trick, I expect - it's just swapping the hard-coded year for the variable containing the input. Or you might have to convert it to an integer first. But that's the general idea. – ADyson Sep 12 '19 at 16:08
  • 1
    Possible duplicate of [Reading an integer from user input](https://stackoverflow.com/questions/24443827/reading-an-integer-from-user-input) – Heretic Monkey Sep 12 '19 at 16:10

1 Answers1

2

name is a string where DateTime need a int to year input argument (like 2019 is).

Convert name to int with :

string name =  Console.ReadLine();
int year = int.Parse(name);

Then you can use year in the DateTime object creation :

DateTime dt = new DateTime(year, mth, 20);
Orace
  • 7,822
  • 30
  • 45
  • It was so Easy! Thank you so very much! – Ngarda Sep 12 '19 at 17:12
  • @Ngarda for the "the 2nd Sunday after the 2nd Tuesday of every month" stuff, look at https://stackoverflow.com/questions/6346119/datetime-get-next-tuesday – Orace Sep 13 '19 at 08:34