mano10
mano10

Reputation: 449

Get Last week date range from sunday to saturday moment js

I need to get last week date range from sunday to saturday, but this code

moment().subtract(1, 'weeks').startOf('isoWeek')
moment().subtract(1, 'weeks').endOf('isoWeek')

gives date range from monday to sunday, How to get Last week date range from sunday to saturday with moment js?

Upvotes: 27

Views: 37306

Answers (2)

Zeeshan DaDa
Zeeshan DaDa

Reputation: 317

Thinking Simply: Set the Week Starting Day first

moment.updateLocale('en', {
    week : {
        dow :0  // 0 to 6 sunday to saturday
    }
});

//than get current week or get last week according to Sun -- Sat
'This Week': [moment().startOf('week'), moment().endOf('week')],
'Last Week': [moment().startOf('week').subtract(7,'days'), moment().endOf('week').subtract(7, 'days')],

you can simply use it with data-ranger in my case i am using "daterangepicker" hopefull you will understand

Upvotes: 2

31piy
31piy

Reputation: 23859

isoWeek gets you the start of week as per ISO 8601 standard. According to international standard ISO 8601, Monday is the first day of the week.

You may try using week instead of isoWeek in the method, which works as per your system settings (locale).

console.log(moment().subtract(1, 'weeks').startOf('isoWeek').format('dddd'));
console.log(moment().subtract(1, 'weeks').endOf('isoWeek').format('dddd'));

console.log(moment().subtract(1, 'weeks').startOf('week').format('dddd'));
console.log(moment().subtract(1, 'weeks').endOf('week').format('dddd'));

console.log(moment().subtract(1, 'weeks').startOf('week').format('YYYY-MM-DD'));
console.log(moment().subtract(1, 'weeks').endOf('week').format('YYYY-MM-DD'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

Read the difference here.

Upvotes: 47

Related Questions