[Fixed] How to get first and last day of the week with Moment.js?

Issue

How do I get the date of the first day of the week and the date of the last day of the week with Moment.js?

I need to get the date from the first day of the week to the date of the last day of the current week that I’m basing on the current day.

I read the documentation https://momentjs.com/docs/ and I found the weekday () function, but I need to get the first day of the week and the last day of the week based on the current date, how do I do this using Moment?

I need this to filter the data of an Observable according to the period: Month, Week …

var start_date = moment(this.start_date, 'DD/MM/YYYY').format('YYYY-MM-DD')
var final_date = moment(this.final_date, 'DD/MM/YYYY').format('YYYY-MM-DD')

this.transacoesList = this.transacoesList
  .filter((v) => {

    var release_date = moment(v.release_date, 'DD-MM-YYYY').format('YYYY-MM-DD');

    if (moment(release_date).isBetween(start_date, final_date, null, '[]')) {
      return true;
    }
  });

Solution

You are on the right track. The weekday function can be used to get the Monday and Friday of the current week.

var now = moment();
var monday = now.clone().weekday(1);
var friday = now.clone().weekday(5);
var isNowWeekday = now.isBetween(monday, friday, null, '[]');

console.log(`now: ${now}`);
console.log(`monday: ${monday}`);
console.log(`friday: ${friday}`);
console.log(`is now between monday and friday: ${isNowWeekday}`);

Direct link to the Moment.js docs on the weekday function here: https://momentjs.com/docs/#/get-set/weekday/

Leave a Reply

(*) Required, Your email will not be published