Determine whether a year is a leap year in C#

This is trivial because the DateTime data type provides an IsLeapYear method to do just this. The example uses the following code to display the leap years between the two entered dates.

// List leap years between the two entered years.
private void btnList_Click(object sender, EventArgs e)
{
    lstYears.Items.Clear();

    int from_year = int.Parse(txtFromYear.Text);
    int to_year = int.Parse(txtToYear.Text);
    for (int year = from_year; year <= to_year; year++)
    {
        if (DateTime.IsLeapYear(year)) lstYears.Items.Add(year);
    }
}

The code uses int.Parse to convert the entered year numbers from strings to integers. It then loops over the years within the indicated range and adds to the ListBox the years for which DateTime.IsLeapYear returns true.

   

 

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.