List birthdays in C#

[birthdays]

Adding values to dates is kind of tricky. For example, you cannot simply add 365 days to a date to get the same date next year because not all years have 365 days.

When you enter a date and click the button, the following code executes to display the same date for the next 10 years and their days of the week.

// Display the next 10 birthdays.
private void btnGo_Click(object sender, EventArgs e)
{
    // Get the month, day, and year of the entered birthday.
    DateTime birthday;
    if (!DateTime.TryParse(txtDate.Text, out birthday))
    {
        MessageBox.Show("Please enter a valid birthday.");
        return;
    }
    int month = birthday.Month;
    int day = birthday.Day;
    int year = birthday.Year;

    // Loop through the years.
    lstBirthDays.Items.Clear();
    for (int i = 0; i <= 10; i++)
    {
        DateTime new_birthday;
        try
        {
            new_birthday = new DateTime(year + i, month, day);
        }
        catch
        {
            new_birthday = new DateTime(year + i, month + 1, 1);
        }
        lstBirthDays.Items.Add(
            new_birthday.ToShortDateString() + " : " +
            new_birthday.DayOfWeek.ToString());
    }
}

The code first uses DateTime.TryParse to try to parse the date you entered. If it cannot parse the date, the program complains and the method returns.

If the date is valid, the program gets its year, month, and day numbers. It then clears the result ListBox and loops through values 0 through 10.

For each value, the program adds the value to the year and uses it to create a new date. If the date is leap year day, then it cannot create the new date. In that case the program sets the new birthdate to March 1 of the same year. (In the United Kingdom the "official" birthdate for leaplings in a non-leap year is March 1, in New Zealand it's February 28, and in the United States there's no official policy.)

The program adds the birthdate to the ListBox and continues its loop.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in algorithms, mathematics and tagged , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *