[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: Find the Friday following a given date in C#

[Find the Friday following a given date in C#]

This example shows how you can find the Friday following a particular date. You can use a similar method to find other days of the week following a specific date. (Note that I have updated this example from its original version to use the technique recommended by Fedor Buyakov in the comments. I've left the comment in to give him full credit for a great suggestion.)

When you enter a date and click the Find Friday button, the following code executes.

// Find the next Friday. private void btnFindFriday_Click(object sender, EventArgs e) { // Get the indicated date. DateTime the_date = DateTime.Parse(txtDate.Text); txtDateLong.Text = the_date.ToLongDateString(); // Find the next Friday. // Get the number of days between the_date's // day of the week and Friday. int num_days = System.DayOfWeek.Friday - the_date.DayOfWeek; if (num_days < 0) num_days += 7; // Add the needed number of days. DateTime friday = the_date.AddDays(num_days); // Display the result. txtFriday.Text = friday.ToShortDateString(); txtFridayLong.Text = friday.ToLongDateString(); }

The code starts by parsing the date you entered and by displaying that date in long format. Next it subtracts the day of the week for that date from the day of the week number for Friday. If the result is less than 0, then the value represents the number of days before the entered date to get to the previous Friday. In that case, the code adds 7 to get the number of days until the next Friday.

The program, then adds the number of days until the next Friday to the indicated date to find the Friday. That's all there is to it.

Download the example to experiment with it and to see additional details.

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