Ngarda
Ngarda

Reputation: 21

C# Looking to type in a Year and pull a date that is placed

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

Upvotes: 2

Views: 50

Answers (1)

Orace
Orace

Reputation: 8359

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

Upvotes: 2

Related Questions