javascript函数返回一年中所有星期日的日期数组 [英] javascript function return date array for all Sundays in a year

查看:110
本文介绍了javascript函数返回一年中所有星期日的日期数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在javascript中编写一个函数,它将返回所有星期日的日期数组。
以下你可以看到我的代码:

i am writing a function in javascript that will return date array of all sundays. below you can see my code :

function getDefaultOffDays(year){
var offdays=new Array();
i=0;
for(month=1;month<12;month++)
{
    tdays=new Date(year, month, 0).getDate();

    for(date=1;date<=tdays;date++)
    {
        smonth=(month<10)?"0"+month:month;
        sdate=(date<10)?"0"+date:date;
        dd=year+"-"+smonth+"-"+sdate;

        day=new Date();
        day.setDate(date);
        day.setMonth(month);
        day.setFullYear(year);

        if(day.getDay() == 0 )
             {              
               offdays[i++]=dd;

             }
    }
}

return offdays;
}

问题是返回的数组给出了随机日期而不是唯一的日期星期日:(
mi缺少一些东西?

the issue is that the returned array is giving random dates not the only dates for sunday :( m i missing some thing?

推荐答案

如果检查结果,你会发现它实际上不是随机的它返回2月份的日期,即2月份的星期日,依此类推。

If you examine the result, you can see that it's actually not random. It returns the dates for january that are sundays in february, and so on.

属性日期对象基于零,而不是基于。如果更改此行,该函数将返回正确的日期:

The month property of the Date object is zero based, not one based. If you change this line, the function will return the correct dates:

day.setMonth(month - 1);

,循环只从1到11,你也需要包括12月:

Also, the loop only runs from 1 to 11, you need to include december too:

for (month=1; month <= 12; month++)






另一种方法将是找到第一个星期日,然后一次只向前迈出七天:


Another way to do this would be to find the first sunday, then just step forward seven days at a time:

function getDefaultOffDays2(year) {
  var date = new Date(year, 0, 1);
  while (date.getDay() != 0) {
    date.setDate(date.getDate() + 1);
  }
  var days = [];
  while (date.getFullYear() == year) {
    var m = date.getMonth() + 1;
    var d = date.getDate();
    days.push(
      year + '-' +
      (m < 10 ? '0' + m : m) + '-' +
      (d < 10 ? '0' + d : d)
    );
    date.setDate(date.getDate() + 7);
  }
  return days;
}

这篇关于javascript函数返回一年中所有星期日的日期数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆