Determine whether a year is a leap year in C#

[leap year]

Detecting leap years is basically 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 into integers. It then loops over the years within the indicated range and adds a year to the ListBox if DateTime.IsLeapYear returns true.


Download Example   Follow me on Twitter   RSS feed   Donate




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

Leave a Reply

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