Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

javascript - JS获得一个月中的周数(moment JS get number of weeks in a month)

I am trying to calculate number of weeks in a month using moment js.

(我正在尝试使用js来计算一个月中的星期数。)

But I am getting wrong results for some months like May 2015 and August 2015.

(但是在2015年5月和2015年8月的几个月中,我得到了错误的结果。)

I am using this code.

(我正在使用此代码。)

var start = moment().startOf('month').format('DD');
var end = moment().endOf('month').format('DD');
var weeks = (end-start+1)/7;
weeks = Math.ceil(weeks);

Is there any prebuilt method in moment JS for getting number of weeks.

(JS矩中是否有任何预构建的方法可以获取星期数。)

  ask by h_a86 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I have created this gist that finds all the weeks in a given month and year.

(我创建了这个要点,可以找到给定月份和年份中的所有星期。)

By calculated the length of calendar , you will know the number of weeks.

(通过计算calendar的长度,您将知道星期数。)

https://gist.github.com/guillaumepiot/095b5e02b4ca22680a50

(https://gist.github.com/guillaumepiot/095b5e02b4ca22680a50)

# year and month are variables
year = 2015
month = 7 # August (0 indexed)
startDate = moment([year, month])

# Get the first and last day of the month
firstDay = moment(startDate).startOf('month')
endDay = moment(startDate).endOf('month')

# Create a range for the month we can iterate through
monthRange = moment.range(firstDay, endDay)

# Get all the weeks during the current month
weeks = []
monthRange.by('days', (moment)->
    if moment.week() not in weeks
        weeks.push(moment.week())
)

# Create a range for each week
calendar = []
for week in weeks
    # Create a range for that week between 1st and 7th day
    firstWeekDay = moment().week(week).day(1)
    lastWeekDay = moment().week(week).day(7)
    weekRange = moment.range(firstWeekDay, lastWeekDay)

    # Add to the calendar
    calendar.push(weekRange)

console.log calendar

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...