I would like to create a function that goes through the months of a given year, calculates how many Fridays fall on the 13th, and returns that number. So far this is what I have:
function numberOfFridaythe13thsIn(jahr){
    var d = new Date();
    d.setFullYear(jahr, 0, 13);
    var counter = 0;
    var months = 0;
    while(months <= 11) {
        months++;
        if(d.getDay() == 5 && d.getDate() == 13) {
          counter++;
       }
    }
    return counter;                            
}
I am imagining this code starts on January 13th of a given year, has a counter where the sum of days will go, and will cycle through the months. I know my code is off, but can I get some guidance?
Try this:
function numberOfFridaythe13thsIn(jahr){
    var d = new Date();
    var counter = 0;
    var month;
    for(month=0;month<12;month++)
    {
     d.setFullYear(jahr, month,13);
        if (d.getDay() == 5)
        {
          counter++;
        }
    }
    return counter;                            
}
Basically, there are only twelve days in the year with date 13. So, we simply loop through each one and check if it is a Friday or not.
The important bit you were missing was to update the date on every loop iteration.
function numberOfFridaythe13thsIn(jahr) {
    var count = 0;
    for (var month=0; month<12; month++) {
        var d = new Date(jahr,month,13);
        if(d.getDay() == 5){
          count++;
       }
    }
    return count;                            
}
console.log(numberOfFridaythe13thsIn(2015));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With