2015-02-07 53 views
0

我正在嘗試計算一個月內使用時刻js的星期數。但是,我在2015年5月和2015年8月的某些月份出現了錯誤的結果。時刻JS獲得一個月內的星期數

我正在使用此代碼。

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

JS中有沒有任何預建方法可以獲得週數。

+0

「開始」和「結束」整數或字符串? – Deepak 2015-02-07 17:04:43

+0

[this]的可能回購(http://stackoverflow.com/questions/21737974/moment-js-how-to-get-week-of-month-google-calendar-style)和[this](http:/ /stackoverflow.com/questions/11448340/how-to-get-duration-in-weeks-with-moment-js)?? – Ethaan 2015-02-07 17:04:51

+1

你會得到什麼結果,你期望什麼? – Xotic750 2015-02-07 17:45:20

回答

0

這是最好的出路,效果很好

moment.relativeTime.dd = function (number) { 
    // round to the closest number of weeks 
    var weeks = Math.round(number/7); 
    if (number < 7) { 
     // if less than a week, use days 
     return number + " days"; 
    } else { 
     // pluralize weeks 
     return weeks + " week" + (weeks === 1 ? "" : "s"); 
    } 
} 

來源:How to get duration in weeks with Moment.js?

1

我創造了這個要點是發現在一個給定的年份和月份衆所周。通過計算calendar的長度,您將知道週數。

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 
+0

請注意,您將需要'moment.js'和'moment-range.js'來運行此腳本。 – guillaumepiot 2015-08-13 17:14:39

3

function getWeekNums(momentObj) { 
    var clonedMoment = moment(momentObj), first, last; 

    // get week number for first day of month 
    first = clonedMoment.startOf('month').week(); 
    // get week number for last day of month 
    last = clonedMoment.endOf('month').week(); 

    // In case last week is in next year 
    if(first > last) { 
     last = first + last; 
    } 
    return last - first + 1; 
} 
3

可以使用原始的javascript很容易做到:

function getNumWeeksForMonth(year,month){ 
       date = new Date(year,month-1,1); 
       day = date.getDay(); 
       numDaysInMonth = new Date(year, month, 0).getDate(); 
       return Math.ceil((numDaysInMonth + day)/7); 
} 

你得到的第一天的日指數,將其添加到數天,以彌補數量在第一週中丟失的天數除以7並使用ceil在下週最簡單的溢出加1 1

+0

這在2017年12月會有不正確的結果。在6周內的結果,而不是5 – 2018-01-20 05:24:26

相關問題