Moment getting the value of the previous month, even after adding one month

Asked

Viewed 993 times

1

I’m trying to work with the Moment js.

var data = moment("2019-08-17", "YYYY-M-D").add('months', 1);

alert(data);

dia = data.date();
mes = data.month();
ano = data.year();

The alert(data) gives me the correct date but when I split mes = data.month(), return the current month and not the calculated one!

Where am I going wrong?

  • Syntax is wrong, change the order .add(1, 'month')

  • Thank you! Indeed, she was like that but recently changed! Vi in the documentation!

1 answer

3


Let’s go in pieces:


Order of parameters in the method add

I don’t know what version of Moment js. you are using, but the documentation of the method add says the following:

Before version 2.8.0, the moment#add(String, Number) syntax was also supported. It has been deprecated in favor of moment#add(Number, String).

In free translation:

Before the version 2.8.0, the syntax moment#add(String, Number) was also borne, but this was depreciated in favour of moment#add(Number, String).

That is to say, add('months', 1) will also work, but when using the most current version of Moment.js, I got a message stating what the documentation indicates:

Deprecation Warning: Moment(). add(period, number) is deprecated. Please use Moment(). add(number, period). See http://momentjs.com/guides/#/warnings/add-Inverted-param/ for more info.

Note: I used the version 2.24.0. To see which one you’re using, just do console.log(moment.version).

Anyway, add('months', 1) works. But by being deprecated, suggest switching to new syntax (add(1, 'months')), if you are using a version >= 2.8.0.


Numerical value of the month

If we look at the documentation of method month, we will see that the value returned is between 0 and 11, because the months are indexed at zero (January is zero, February is 1, etc). Probably was done so to maintain compatibility with the Date javascript native, that has this same behavior.

That is, simply add 1 to get the correct numerical value (January equal to 1, February equal to 2, etc):

// usar a sintaxe nova: add(numero, string)
let data = moment("2019-08-17", "YYYY-M-D").add(1, 'months');

console.log(data);

let mes = data.month() + 1; // somar 1 pois janeiro é zero, fevereiro é 1, etc
console.log(mes); // 9
<script src="https://momentjs.com/downloads/moment.min.js"></script>

Only one point of attention: although the months are indexed in zero, the constructor that takes two strings (one with the date and one with the format) considers the correct values of the month. That’s why moment("2019-08-17", "YYYY-M-D") creates a date in August. But by obtaining the numeric value in the method month, then the January rule is used to be zero. Confusing, but that’s how it was done.


Another option to get the month value is to use format, who doesn’t use the "January is zero rule":

// usar a sintaxe nova: add(numero, string)
let data = moment("2019-08-17", "YYYY-M-D").add(1, 'months');

console.log(data);

console.log(data.format('M')); // 9

// com o zero antes, caso o mês seja menor que 10
console.log(data.format('MM')); // 09
<script src="https://momentjs.com/downloads/moment.min.js"></script>

The difference is that month() returns a number, while format returns a string. Depending on what you will do with this value, it can make a difference.


As to the your comment, about putting the value in a input date, to documentation says that, to set a date to this input, the value must be in the format ISO 8601 ("yyyy-mm-dd"). This can be obtained using format. Ex:

document.addEventListener('DOMContentLoaded', (event) => {
    let data = moment("2019-08-17", "YYYY-M-D").add(1, 'months');
    document.querySelector('#mesQueVem').value = data.format('YYYY-MM-DD');
});
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<form>
  <div>
    <input type="date" id="mesQueVem" name="mesQueVem">
  </div>
</form>

  • So far I went well but I happen to catch the return of Moment already increased the number of days and I want to play it in an input type date. Know if possible? And how? If it is not possible, how to get rid of the problem that when making mes = date.Month();, the variable month and day receives, for values less than 10, its value without the 0 in front and then I have problem sending this data to the input.

  • @Carlosrocha On the input date and the value with zero in front, I put an example of each. But if that’s not what you need, please edit the question in more detail.

  • This may be happening because you have put the date format as 'YYYY-M-D' changes the format to ``` 'YYYY-MM-DD'````

  • @Robsonsilva No Parsing it makes no difference, see. It would make a difference if "YYYY-M-D" was used in format.

  • @hkotsubo, it’s true, so try to add the .format('YYYY-MM-DD) at the end, and the indented values will be with the ones with the 0 in front of the dates that are necessary. var data = moment("2019-08-17", "YYYY-M-D").add('months', 1).format('YYYY-MM-DD);

  • @Robsonsilva But in the last example of code I already do this...

  • @hkotsubo, so that’s right, I think it will be the best way out.

Show 2 more comments

Browser other questions tagged

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