Find out the date of the Friday following a given date in C#

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;

    // Make a TimeSpan representing num_days days, 0 hours, 0 minutes, 0 seconds.
    TimeSpan days_until_friday = new TimeSpan(num_days, 0, 0, 0);

    // Add the TimeSpan to the_date.
    DateTime friday = the_date + days_until_friday;

    // Display the result.
    txtFriday.Text = friday.ToShortDateString();
    txtFridayLong.Text = friday.ToLongDateString();
}

The code starts by parsing the date you entered and 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, converts the number of days until the next Friday into a TimeSpan representing that many days as elapsed time. It adds the TimeSpan to the entered date and displays the result in short and long format.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments

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.