Date in Javascript with October 31st

Asked

Viewed 249 times

3

I am trying to find the due date adding the date, but I realized that the function does not return me the day 31 October 2019.

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

var data = new Date('2019','10','01');
data.setDate( + 31  ) ;
console.log( data.getDate() + ' / ' + data.getMonth() + ' / ' +data.getFullYear());
  • Why the function should return 31 if you are adding 31 to 1?

  • Exact, but if I put 30 returns me '30 / 10 / 2019'.

2 answers

3

The problem and how you are initiating the Date note:

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);

Parameters for the Date constructor
Note: When Date is called as a constructor with more than one argument, if the values are greater than their logical limit (e.g. if 13 is given as a value for month or 70 is the value for minute), the adjacent value will be adjusted. 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 to 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 1900 to 1999.

mês: An integer value representing the month, starting with 0 for January until 11 for December. dia: An integer value representing the day of the month.
  • 1

    Got it, the month starts with 0 ( zero ). Thanks!!!

0

In the Date of Javascript, the months are indexed at zero (January is zero, February is 1, etc). So new Date('2019','10','01') creates a date for 1 November 2019.

When setting the day to 31, the result is December 1, 2019 (because November does not have 31 days, then the value 31 ends up being adjusted for the following month), and how getMonth() also follows the rule to be indexed at zero, it returns 11, and you end up with the result "1/11/2019".

Then just pass the value 9 for 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());

In fact, an important detail: setDate(+31) is changing the day to 31. He’s not adding 31 days, and the sign of more makes no difference (+31 is the same as the number 31). Proof of this is that the date can start on any day, 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)) not totaled 31 days, only changed the value of the day to 31 (see the documentation).


Now if you always want the last day of the month, regardless of the date, setting the day to 31 will not work for all cases (since some months have 30 days, and February may 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

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

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


Moment js.

Another alternative is to use the 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 forms. The first two use the zero-indexed month rule, and the third uses the correct value.

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

If you need to get a Date Javascript, just do it d.toDate().

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

Browser other questions tagged

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