[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: List birthdays in C#

[List birthdays in C#]

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 the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.