Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy way to determine leap year in ruby?

Is there an easy way to determine if a year is a leap year?

like image 296
MikeJ Avatar asked Oct 14 '09 14:10

MikeJ


People also ask

What is the easiest way to identify a leap year?

Any year that is evenly divisible by 4 is a leap year: for example, 1988, 1992, and 1996 are leap years.

How do you check if a year is leap year without using any operators?

If a year is a century year, meaning divisible by 100, then it needs to be divisible by 400 to be called as a leap year. If a year is not a century year, then it needs to be divisible by 4 to be called as a leap year.

What is leap year algorithm?

The algorithm to determine if a year is a leap year is as follows: Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100, but these centurial years are leap years, if they are exactly divisible by 400.

How is leap month calculated?

To determine when, find the number of new moons between the 11th month in one year and the 11th month in the following year. A leap month is inserted if there are 13 New Moons from the start of the 11th month in the first year to the start of the 11th month in the next year.


2 Answers

Use Date#leap?.

now = DateTime.now  flag = Date.leap?( now.year )  

e.g.

Date.leap?( 2018 ) # => false  Date.leap?( 2016 ) # => true 
like image 61
Mitch Wheat Avatar answered Oct 05 '22 23:10

Mitch Wheat


For your understanding:

def leap_year?(year)   if year % 4 == 0     if year % 100 == 0       if yearVar % 400 == 0         return true       end       return false     end     return true   end   false end 

This could be written as:

def leap_year?(year)   (year % 4 == 0) && !(year % 100 == 0) || (year % 400 == 0) end 
like image 22
Aldrine Einsteen Avatar answered Oct 06 '22 00:10

Aldrine Einsteen