Home > database >  Date checker program
Date checker program

Time:11-03

I'm creating a little program to give dates for a game. My question is how can I check that the date the program gives me was a real date in the past? For example the lenght of February in a selected year.

My current method is selecting a year and a month from a ComboBox and then it generates 20-60 dates. Then I have a date, for example 02.02.1999. Then it starts to fill labels with dates with this code:

//Fill labels
            int day1 = int.Parse(day);
            for (int i = 1; i < lenght1; i  )
            {
                var labels = Controls.Find("lbl_date_"   i, true);
                var label = (Label)labels[0];
                label.Text = Convert.ToString(day1)   "."   month   "."   year;
                day1  ;
                string date_curr = Convert.ToString(label.Text);

My goal is to check every date's reality after every cycle and if it is not valid (32nd day of a month etc.) then add 1 to the month. And if I run out of months then add 1 to the year.

Thank you.

CodePudding user response:

ou can use DateTime.DaysInMonth() method to get the number of days in a given month:

int days = DateTime.DaysInMonth(2000, 2); //year: 2000, month: 2

CodePudding user response:

Here's an example showing how to use DateTime.AddDays():

// these really come from your ComboBoxes
String day = "30"; // to show that it will roll over into November
String month = "10";
String year = "2021";
int lenght1 = 30;

DateTime dt;
if (DateTime.TryParseExact(day   "."   month   "."   year, "d.M.yyyy", null, DateTimeStyles.None, out dt))
{
    for (int i = 1; i < lenght1; i  )
    {
        Label label = Controls.Find("lbl_date_"   i, true).FirstOrDefault() as Label;
        if (label != null)
        {
            label.Text = dt.ToString("d.M.yyyy");
        }
        dt = dt.AddDays(1);                   
    }
}
else
{
    MessageBox.Show("Invalid Start Date");
}
  • Related