Date in JavaScript with October 31st

I am trying to get the due date by adding the date, but I realized that the function does not return me on October 31 of the Year 2019.

Follows the code below that returns me '1 / 11 / 2019' and it should return to me '31 / 10 / 2019':

var data = new Date('2019','10','01');
data.setDate( + 31  ) ;
console.log( data.getDate() + ' / ' + data.getMonth() + ' / ' +data.getFullYear());
Author: hkotsubo, 2019-10-15

2 answers

The problem and how you are booting the Date notes:

var data = new Date('2019','10','01');
console.log( "new Date('2019','10','01')", 'NOVEMBRO', data.toLocaleDateString(), 'getMonth:', data.getMonth() )

var data = new Date('2019','0','01');
console.log( "new Date('2019','0','01')", 'JANEIRO' , data.toLocaleDateString(), 'getMonth:',data.getMonth() );

var data = new Date('2019','09','01');
console.log(  "new Date('2019','09','01')", 'OUTUBRO', data.toLocaleDateString(), 'getMonth:',data.getMonth() )

new Date(ano, mês, dia, hora, minuto, segundo, milissegundo);

the Parameters to the constructor for Date
Note: where Date is called as a constructor with more than one argument, if values are greater than its threshold logic (e.g. 13 is provided as the value for the month, or 70 is the value for min) the value of the adjacent one will be set. E. G. new Date(2013, 13, 1) is equivalent to new Date(2014, 1, 1), both create a date for 2014-02-01 (note that the month starts at 0) . Similarly for other values: new Date(2013, 2, 1, 0, 70) is equivalent to new Date(2013, 2, 1, 1, 10), as both create a date for 2013-03-01T01:10:00.

ano: An integer value representing the year. Values from 0 to 99 correspond to the years from 1900 to 1999.

mês: An integer value that represents the month, starting with 0 for January until 11 for December. dia: Value integer representing the day of the month.
 3
Author: Icaro Martins, 2019-10-15 16:17:43

No Date from JavaScript, the months are indexed to zero (January is zero, February is 1, etc). Then new Date('2019','10','01') creates a date referring to November 1, 2019.

When setting the day to 31, the result is December 1, 2019 (since November does not have 31 days, so the value 31 ends up undergoing an adjustment for the following month), and how getMonth() it also follows the rule of being indexed to zero, it returns 11, and you end up having as a result "1/11/2019".

Then it would be enough to pass the value 9 to the month, and add 1 to the return of getMonth():

let data = new Date(2019, 9, 1);
data.setDate(31);
console.log( data.getDate() + ' / ' + (data.getMonth() + 1) + ' / ' + data.getFullYear());

Incidentally, an important detail: setDate(+31) is changing the day to 31. it is not adding up 31 days, and the plus sign makes no difference (+31 is the same as the number 31). Proof of this is that the date can start on any day, that the result will be day 31:

let data = new Date(2019, 9, 30);
data.setDate(+31);
console.log(`${data.getDate()}/${data.getMonth() + 1}/${data.getFullYear()}`);

Even starting with a date on the 30th, setDate(+31) (which is the same as setDate(31)) did not add up to 31 days, just changed the day value to 31 (see documentation).


Now if you always want the last day of the month, regardless of the date, setting the day to 31 won't work for all cases (since some months have 30 days, and February can have 28 or 29). So what you can do is create a date referring to the first day of the following month and subtract 1 day:

// 1 de novembro de 2019
let d = new Date(2019, 10, 1);
d.setDate(d.getDate() - 1); // subtrai 1 dia

// mostra a data no formato dd/mm/yyyy
console.log(d.toLocaleDateString('pt-BR')); // 31/10/2019
// ou, se quiser formatar manualmente
console.log(`${d.getDate().toString().padStart(2, '0')}/${(d.getMonth() + 1).toString().padStart(2, '0')}/${d.getFullYear()}`); // 31/10/2019

Notice that the values passed to the constructor can be numbers instead of strings (incidentally, is the type expected by the constructor).

To format the date, I did two ways: using toLocaleDateString, which uses predefined formats based on locale (in the case I used pt-BR, which corresponds to "Brazilian Portuguese", which has the format dd/mm/yyyy), and formatting manually (using padStart to complete with zero on the left when the value is less than 10).


Moment.js

Another alternative is to use Moment.js :

// várias maneiras de criar "1 de outubro de 2019"
let d = moment([2019, 9, 1]);
d = moment({ year: 2019, month: 9, day: 1 });
d = moment('2019-10-01'); // nesse caso o mês é 10 mesmo

// último dia do mês
d.endOf('month');
console.log(d.format('DD/MM/YYYY')); // 31/10/2019
<script src="https://momentjs.com/downloads/moment.min.js"></script>

First I create the date, and see that there are several different ways. The first two use the rule of the month indexed at zero, and the third uses the correct value.

Then I use the method endOf to get the end of the month, and the method format to show the date in a specific format.

If you need to get a Date from JavaScript, just do d.toDate().

Remembering that endOf also changes the time, as explained in detail in this answer.

 0
Author: hkotsubo, 2019-10-19 11:42:49