Moment.js how to get week of month? (google calendar style)

后端 未结 12 836
挽巷
挽巷 2020-12-03 13:56

I am using Moment.js and it is great. The problem I have now is that I can\'t figure out how to get the week of the month a certain date is. I can only find \"week of year\"

12条回答
  •  旧时难觅i
    2020-12-03 14:37

    Here's Robin Malfait's solution implemented with the lightweight library date-fns

    import {
        differenceInDays,
        startOfMonth,
        startOfWeek,
        getDate
    } from 'date-fns'
    
    const weekOfMonth = function (date) {
        const firstDayOfMonth = startOfMonth(date)
        const firstDayOfWeek = startOfWeek(firstDayOfMonth)
        const offset = differenceInDays(firstDayOfMonth, firstDayOfWeek)
        return Math.ceil((getDate(date) + offset) / 7)
    }
    
    export default weekOfMonth
    

提交回复
热议问题