javascriptecmascript-6momentjsjavascript-objectsecmascript-5

How to get start and end dates from this iso formated structure using moment.js?


I have the related.date: {"isoYear":"2021","isoWeek":"31"} property with the following value received from the backend. How can I receive first date and last date from isoWeek 31 for the isoYear by using momenjs?


Solution

  • You could use startOf('isoWeek') and endOf('isoWeek') after you get isoYear from object and add isoWeek weeks:

    let related = {"isoYear":"2021","isoWeek":"31"};
    
    console.log(moment(related.isoYear, 'YYYY').add(parseInt(related.isoWeek), 'weeks').startOf('isoWeek').format('DD/MM/YYYY'))
    
    console.log(moment(related.isoYear, 'YYYY').add(parseInt(related.isoWeek), 'weeks').endOf('isoWeek').format('DD/MM/YYYY'))
    
    console.log(moment(related.isoYear, 'YYYY').add(parseInt(related.isoWeek), 'weeks').startOf('month').format('DD/MM/YYYY'))
    
    console.log(moment(related.isoYear, 'YYYY').add(parseInt(related.isoWeek), 'weeks').endOf('month').format('DD/MM/YYYY'))
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>

    EDIT

    Now if you want to get month from month property you could do:

    let related = {"isoYear":"2021","isoWeek":"31", "month": "06"}
    
    console.log(moment(related.isoYear, 'YYYY').add(parseInt(related.month) - 1, 'months').startOf('month').format('DD/MM/YYYY'))
    
    console.log(moment(related.isoYear, 'YYYY').add(parseInt(related.month) - 1, 'months').endOf('month').format('DD/MM/YYYY'))
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>

    Note the -1 on add function: this because in moment months number start from 0 (January).