admin管理员组文章数量:1313789
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?
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?
Share Improve this question edited Nov 4, 2015 at 6:02 LearningProcess 6131 gold badge9 silver badges29 bronze badges asked Nov 4, 2015 at 5:55 vehckloxvehcklox 451 silver badge6 bronze badges 2-
What is being passed in?
jahr
– LearningProcess Commented Nov 4, 2015 at 5:58 -
@LearningProcess
jahr
is a year in the format of yyyy. For instance 1977. – vehcklox Commented Nov 4, 2015 at 6:01
3 Answers
Reset to default 5Try 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));
I think it will help you...
function numberOfFridaythe13thsIn(jahr) {
var counter = 0;
for (i = 1; i <= 12; i++) {
var d = new Date(i + "/13/" + jahr);
if (d.getDay() == 5) {
counter++;
}
}
return counter;
}
it is for MM/dd/yyyy format.
本文标签: javascriptCount the number of Friday39s that fall on the 13th within a given yearStack Overflow
版权声明:本文标题:javascript - Count the number of Friday's that fall on the 13th within a given year - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741955511a2406966.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论