首页 > 编程 > JavaScript > 正文

JS获取月的第几周和年的第几周实例代码

2019-11-19 12:24:33
字体:
来源:转载
供稿:网友

下面一段代码给大家介绍JS获取月的第几周和年的第几周,具体代码如下所述:

var getMonthWeek = function (a, b, c) {      /*      a = d = 当前日期      b = 6 - w = 当前周的还有几天过完(不算今天)      a + b 的和在除以7 就是当天是当前月份的第几周      */      var date = new Date(a, parseInt(b) - 1, c), w = date.getDay(), d = date.getDate();      return Math.ceil(        (d + 6 - w) / 7      );    };    var getYearWeek = function (a, b, c) {      /*      date1是当前日期      date2是当年第一天      d是当前日期是今年第多少天      用d + 当前年的第一天的周差距的和在除以7就是本年第几周      */      var date1 = new Date(a, parseInt(b) - 1, c), date2 = new Date(a, 0, 1),        d = Math.round((date1.valueOf() - date2.valueOf()) / 86400000);      return Math.ceil(        (d + ((date2.getDay() + 1) - 1)) / 7      );    };    //获取时间的代码就不写了    console.log(getMonthWeek(2019,1,1));//返回1

 补充:js 获取每月有几周,当前时间在当月第几周,今天周几等方法

 因产品需要展示相关时间,现总结如下方法:以供日后参考:

获取每月有几周

 // year:年 month:月 day:日 getWeeks(year, month, day) {  const d = new Date()  // 该月第一天  d.setFullYear(2018, 6, 1)  let w1 = d.getDay()  if (w1 === 0) {   w1 = 7  }  // 该月天数  d.setFullYear(2018, 7, 0)  const dd = d.getDate()  // 该月第一个周一  let d1  if (w1 !== 1) {   d1 = 7 - w1 + 2  } else {   d1 = 1  }  const WEEK_NUB = Math.ceil((dd - d1 + 1) / 7)  return WEEK_NUB }

获得周期名字

getWeekName() { const weekday = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'] const index = new Date().getDay() const currDay = weekday[index] return currDay}

获得当前日期在当月第几周

  // a: 年 b: 月 c: 日 (不包括跟上个月重合的部分)  getMonthWeek(a, b, c) {   const date = new Date(a, parseInt(b) - 1, c)   const w = date.getDay()   const d = date.getDate()   return Math.ceil(    (d + 6 - w) / 7   )  }

总结

以上所述是小编给大家介绍的JS获取月的第几周和年的第几周实例代码 ,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表