Find the Friday following a given date in C#

[find the Friday]

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 Example   Follow me on Twitter   RSS feed   Donate

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

2 Responses to Find the Friday following a given date in C#

  1. // Make a TimeSpan representing num_days days, 0 hours, 0 minutes, 0 seconds.

    // Add the TimeSpan to the_date.

    why not to simplify:
    DateTime friday = the_date.AddDays(num_days);

  2. Rod Stephens says:

    That works, and is slightly simpler. I think I just had TimeSpans on the brain.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.