List your next 10 birthdays and their days of the week 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 = DateTime.Parse(txtDate.Text);
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 = new DateTime(year + i, month, day);
lstBirthDays.Items.Add(
new_birthday.ToShortDateString() + " : " +
new_birthday.DayOfWeek.ToString());
}
}

The code first parses the date you entered and creates a DateTime variable from it. It then gets the date's month, day, and year.

Next the code loops through values 0 through 10. For each value, it adds the value to the year, creates a new date, and adds the date and its day of the week to the ListBox.

  

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.