How to catch the start and end of the week on Moment.js

Asked

Viewed 1,540 times

1

I use the following code to catch the start and end of the week.

pegaData() {
    moment().locale();
    var agora;
    var datainicial;
    var datafinal;
    agora = moment().format('DD-MM-YYYY');
    console.log(agora);
    if(agora = 'Thusday'){
        datainicial = moment().subtract(4, 'days').calendar();
        datainicial = moment().format('DD-MM-YYYY');
        datafinal = moment().add(2, 'days').calendar();
        datafinal = moment().format('DD-MM-YYYY');

    }
    console.log(datainicial);
    console.log(datafinal);
}

And the code returns right the initial and final date, only not in the format I need, which would be 'DD-MM-YYYY'.

But at the moment of conversion, as I call the again, it converts the current date, as I can format the date without calling the again?

1 answer

1


If you want to change the day of the week, just use the method day, passing a value between zero (Sunday) and 6 (Saturday):

let agora = moment();

let inicio = moment().day(0); // domingo desta semana
let fim = moment().day(6); // sábado desta semana

// imprimir as datas no formato desejado
let formato = 'DD/MM/YYYY';
console.log('agora=', agora.format(formato));
console.log('início=', inicio.format(formato));
console.log('fim=', fim.format(formato));
<script src="https://momentjs.com/downloads/moment.min.js"></script>

So you don’t need to be doing multiple tests, as you were doing ("if today is fifth, sum 2 days, etc").

Then you assign the result of each one to a variable and use format to display them in the desired format.

In the code above, as today is 30/05/2019, then the initial value will be 26/05/2019, and the final value will be 01/06/2019.

  • 1

    Thank you very much man, where I saw about the day method Moment.js did not have, thank you very much for showing me it, helped too much!!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.