Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check leap year in C#

Tags:

c#

I want to add entry date + 1year to a column called finishing date.

If the entry date is in leap yr, i need to add 364 days, if not 365 days.

Is there a way to check this in c#, using current datetime's year & manipulate leap yr/not, then add the days.

Thanks.

like image 437
Sharpeye500 Avatar asked Nov 08 '10 21:11

Sharpeye500


People also ask

What is leap year formula?

2020 /4 = 505 - 2020 is a leap year. After you divide the year by 4, the obtained number should be an integer. That means that its remainder must be equal to 0. If your year has two zeros at the end (e.g., 1700) you should also check if it can be divided by 400, leaving no remainder.

Is 2022 a leap year?

Why 2022 isn't a leap year. The last leap year was 2020. So 2024 will be our next leap year, a 366-day-long year, with an extra day added to our calendar (February 29). We'll call that extra day a leap day.


1 Answers

You can use the DateTime.IsLeapYear method.

But just for handling that you do not really need to use that method. DateTime.AddYears takes leap years into account.

var leapYear = new DateTime(2000, 2, 29);
Console.WriteLine("Is 2000 a leap year? {0}", DateTime.IsLeapYear(leapYear.Year)); // 2000 is a leap year
Console.WriteLine("One year added to {0} is {1}", leapYear, leapYear.AddYears(1)); // 2000-02-29 plus 1 year is 2001-02-28
like image 150
Patko Avatar answered Sep 21 '22 15:09

Patko