如何在JS中获取给定星期数的日期范围 [英] How to get the date ranges of a given week number in JS

查看:99
本文介绍了如何在JS中获取给定星期数的日期范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果该周恰好是连续2个月,则我需要知道该周的确切月份.例如,2016年的第52周分别在2016年12月和2017年1月.2017年的第5周也从2017年1月30日至2月5日开始.

I need to know the exact months that a week falls in if that week happens to be in 2 consecutive months. For example 52nd week of 2016 falls in Dec 2016 and January 2017.Also 5th week of 2017 starts on 30th January - 5th February 2017.

因此,给定一年中的第几周,我可以得到它的月份数.我需要知道是否有任何JS库可以轻松实现这一目标.

So given a week number in a year, can I get the months it falls in. I need to know if there is any JS library that can easily achieve this.

我知道我可以从特定的日期值中获取星期数,但还没有找到获取日期所属日期范围的方法,以便可以从中得出月份. momentJS或任何其他lib都可以做到这一点,如何使用它们来实现这一点?

I know I can get a week number from a specific date value but have not seen a way to get a range of dates that date falls in so that I can derive the months from there.If momentJS or any other lib can do this, how can I use them to achieve this?

预先感谢

推荐答案

我们要为给定星期的开始和结束创建日期对象.

We want to create a date object for the beginning of a given week and the end.

momentjs 是一个很好的库,可简化日期对象的使用.

momentjs is a good library to make using date objects much easier.

var moment = require('moment');

function getMonths(weekNumber) {
  var beginningOfWeek = moment().week(weekNumber).startOf('week');
  var endOfWeek = moment().week(weekNumber).startOf('week').add(6, 'days');
  console.log(beginningOfWeek.format('MMMM'));
  console.log(endOfWeek.format('MMMM'));
}

给出一个星期的数字,我们将创建一个矩对象,然后再创建一个六天的对象.然后我们将月份记录在一周的开始和结束.

Given a week number, we are creating a moment object and another one six days later. Then we log the month at the beginning and end of the week.

这是一个例子:

getMonths(5);

一月

二月

这篇关于如何在JS中获取给定星期数的日期范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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