js取得当年每周的起始日期

最近做项目的时候,遇到了这个问题,js获得当年每周的信息,并且罗列出来。代码贴出来。

var getWeeks = function(year){

     var d = new Date(year, 0, 1);

     while (d.getDay() != 1) {

        d.setDate(d.getDate() - 1);

     }

     var to = new Date(year + 1, 0, 1);

     var i = 1;

     for (var from = d; from < to;) {

        var str = '';

        str = str + "第" + i + "周 " +year+"-"+ ((from.getMonth() + 1)<=9?('0'+(from.getMonth() + 1)):(from.getMonth() + 1)) + "-" + (from.getDate()<=9?('0'+from.getDate()) : from.getDate()) + " 至 ";

        from.setDate(from.getDate() + 6);

        if (from < to) {

           str = str + year +"-"+ ((from.getMonth() + 1)<=9?('0'+(from.getMonth() + 1)):(from.getMonth() + 1)) + "-" + (from.getDate()<=9?('0'+from.getDate()) : from.getDate());

           from.setDate(from.getDate() + 1);

        } else {

            to.setDate(to.getDate() - 1);

            str = str + year +"-"+ ((to.getMonth() + 1)<=9?('0'+(to.getMonth() + 1)):(to.getMonth() + 1)) + "-" + (to.getDate()<=9?('0'+to.getDate()) : to.getDate());

         }

          console.log(str)

          i++;

    }

}
getWeeks(2017)

你可能感兴趣的:(js取得当年每周的起始日期)