0

I am looking for a way to find the list of leap years between the birth year and today and print them.

function listOfLeapYears(aYear) 
{
aYear = birthDate.getFullYear()
bYear = today.getFullYear()

document.write(aYear + '<br>')
document.write(bYear + '<br>')

    for (i = aYear; i <= bYear; )
    {
        if (isLeapYear(birthDate))
        {
        document.write(i + '<br>');
        }
    birthDate.setFullYear(i+1)
    } 
}

var birthYear, birthMonth, birthDay
    birthYear = parseFloat(window.prompt('please enter your birth year' + ''))
    birthMonth = parseFloat(window.prompt('please enter your birth month' + ''))
    birthDay = parseFloat(window.prompt('please enter your birth day' + ''))

birthDate = new Date(birthYear, birthMonth-1, birthDay)
today = new Date()

document.write('your birth date is ' + dateStringLong(birthDate) + '<br>')
document.write('you are ' + differenceInYears(today, birthDate) + ' years old' + '<br>' )

listOfLeapYears(birthDate)

the for loop with the if statement doesn't seems to work as expected. What I want my program to do for example:

birthyear is 1991

today = 2016 is 1991 leap year => yes print it
=> no move to the next year is 2016 leap yes => yes print it
=> no stop ( because it is equal to today year )

Jason Aller
  • 3,541
  • 28
  • 38
  • 38

1 Answers1

0

I think that you can minify your code by this way:

function listOfLeapYears(birthYear) {

  var 
    leapYear,
    count = 0,
    i;

  leapYear = function(year) {

    // leapYear function source: http://stackoverflow.com/questions/16353211/check-if-year-is-leap-year-in-javascript?answertab=active#tab-top

    return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
  };

  i = new Date().getFullYear();

  for (; i >= birthYear; i--) {

    if (leapYear(i)) {

      count++;
      document.write(i + '<br>');
    }
  }

  document.write('<br>Count: ' + count);
}

listOfLeapYears(birthYear);

You don't need month and day to get leap years list.

Input: 1988
Output: 2016, 2012, 2008, 2004, 2000, 1996, 1992, 1988

Ali Mamedov
  • 5,116
  • 3
  • 33
  • 47